Parsed elements coming up as undefined - javascript

I'm trying to parse the following JSON:
{
"customers": [
{ "name":"joe" , "cars":[
{"name":"honda","visits":[
{"date":"01/30/14","Id":"201"},
{"date":"01/30/14","Id":"201"},
{"date":"02/12/14","Id":"109"}
]},
{"name":"Nissan","visits":[
{"date":"01/30/14","Id":"201"},
{"date":"02/12/14","Id":"109"}
]}
]},
{ "name":"bob" , "cars":[
{"name":"escalade","visits":[
{"date":"01/05/14","Id":"301"},
{"date":"01/18/14","Id":"551"}
]},
{"name":"corvette","visits":[
{"date":"01/05/14","Id":"301"},
{"date":"01/18/14","Id":"551"}
]}
]}
]
}
Using the following jQuery script:
$("document").ready(function(){
$.getJSON("data1.json", function(json) {
console.log(json); // this will show the info it in firebug console
$.each(json.customers,function(customer){
console.log(customer.name);
console.log(customer.cars);
});
});
});
The JSON is coming through in the console but the fields I'm trying to parse are coming up as undefined. Can anyone ell me what I'm doing wrong?

I think the issue here is your usage of $.each, your callback function will receive the index as the first argument and the value as the second argument and it looks like you are expecting the first argument to be the value. So in your current code customer will be an index (0, 1, etc.) rather than the object from your JSON.
Try changing your $.each call to the following:
$.each(json.customers, function(index, customer) {
console.log(customer.name);
console.log(customer.cars);
});

Related

Rendering Mongo document values in Pug template w/ Express

I'm retrieving documents from Mongo Atlas using the new data API like this :
axios(config)
.then(function (response) {
console.log(response.data);
res.render('profile', {
snippets: response.data,
})
.catch(function (error) {
console.log(error);
});
};
My console.log(response.data) shows the documents correctly like this :
documents: [
{
_id: '6245b82edde6452fece5d27d',
snippet: '<p>This is a test post in <strong>bold, </strong>in <em>italic, </em>in <span style="text-decoration: underline;">underline,</span> and with a link</p>'
},
{
_id: '6245b8fbe9d255ab42528197',
snippet: '<p>This is a test post in <strong>bold, </strong>in <em>italic, </em>in <span style="text-decoration: underline;">underline,</span> and with a link. A second time!</p>'
}
]
}
Then I followed this answer to try render a simple list of these of the snippet values in a table :
table
each snippet in snippets
tr#snippet_list_item
td #{snippet._id}
td #{snippet.snippet}
But I get
snippets include [object Object],[object Object]
rendered on the front end instead of the values.
What am I missing? My thinking was... pass the objects, iterate through, access the values for each. But I'm obviously not doing something right.
Okay so for people coming to this whilst still learning...
If you ever get this problem, where you are trying to access values inside an array of objects and are getting 'Object Object', make sure to look at the structure of the data you are getting.
See below
documents: [
{
_id: '6245b82edde6452fece5d27d',
snippet: '<p>This is a test post in <strong>bold, </strong>in <em>italic, </em>in <span style="text-decoration: underline;">underline,</span> and with a link</p>'
},
{
_id: '6245b8fbe9d255ab42528197',
snippet: '<p>This is a test post in <strong>bold, </strong>in <em>italic, </em>in <span style="text-decoration: underline;">underline,</span> and with a link. A second time!</p>'
}
]
}
My data is structured like this :
'documents'[
{document 1}
{document 2}
]
Each {document} is an object. But they are all inside an array of objects, which in my case is 'documents'. You can see this by the [] square brackets that the {documents} are contained inside.
So when accessing the values, you first need to access the array by response.data.{$name_of_array}, THEN, you can use dot notation to access the values
so to access the values, you'd do something like :
response.data.{$name_of_array}.{$name_of_value_name}
if accessing all of these, you'll need to iterate through them, if accessing just 1, you can use it's position in the index like this :
response.data.{$name_of_array}[$index_number].{$name_of_value_name}
Hope this helps someone!

finding nested object value in java script

JSON file from URL
{
"1": [
{
"actions": ["OUTPUT:2" ],
"idle_timeout": 0,
"cookie": 0,
"packet_count": 2,
"hard_timeout": 0
}
}
JavaScript
function myFunction() {
//alert("INTo function");
$.ajax({
url: "http://127.0.0.1:3000/flow",
cache: false,
success: function(data) {
$("#flow").append(data["1"].actions.OUTPUT[i]);
$("#flow").append(data["1"].idle_timeout);
$("#flow").append(data["1"].cookie);
$("#flow").append(data["1"].packet_count);
$("#flow").append(data["1"].hard_timeout);
}
});
}
This is the JavaScript code which I have used it, to find values of the object inside the nested JSON response coming from a URL.
Your sample does not look like valid json. Since the value of "1" is an array, you should try to access it via the index. e.g.$("#flow").append(data["1"][0].idle_timeout)
The code used to find the values inside the nested JSON object is actually incorrect.
You must use data["1"][0].actions[0].OUTPUT to retrieve the value 2.

jQuery: Get JSON error

I'm trying to get certain elements from a JSON file but I'm just not able to do so, I've tried different ways, this is the JSON file:
// data.json
{
"stuff": [
{
"userId": 1,
"date": "19 Oct 2014",
"content": "#New Hello on g.co/ABC",
"entities": {
"hashtags": ["#New"],
"urls": ["g.co/ABC"]
}
}
],
"user": {
"avatar": "/assets/avatar.jpg",
"name": "Daniel"
}
}
Now my jQuery code is:
$(document).ready(function(){
$.getJSON('data.json', function(data) {
//console.log(data);
$.each(data,function(i,item){
console.log(item.stuff.content); // I want to print 'content'
});
});
});
And all I get is an Uncaught error type:
What am I doing wrong? Thanks in advance
stuff is an array of object.
To access item of an array you have to access it via index
like this
console.log(data.stuff[0].content);
JSFIDDLE
May be you are iterating an object instead of array of object
If data is an object then try like this
$.each(data.stuff,function(i,item){
console.log(item.content);
});
JSFIDDLE
This should work:
$.getJSON('data.json', function(data) {
console.log(data['stuff'][0]['content']);
}
It is getting the stuff element of the JSON object then the first element of that pair, since the pair of key "stuff" is an array of JSON Objects. Then from that last JSON object, its grabbing content.
You json data is not an array. so you don't need to use each. But stuff is an array so take it's specific index or loop through it.
$(document).ready(function(){
$.getJSON('data.json', function(data) {
console.log(data.stuff[0].content);
//or loop through like
//$.each(data.stuff,function(i,item){
// console.log(item.content);
//});
});
});

Not able to set text in input field from json response

I have a form in which I have to fill data after I have got a json object from httpGet in javascript.
$("#getDetails").click(function() {
$.get("/servlet",{
mID : 5
})
.done(function(data) {
$("#input1").val(data["some key"]);
$("#input2").val(data.name);
$("#input3").val("directvalue");
});
});
In the above 3 fields, only input3 gets filled with "directvalue".
Is there some problem in accessing json object or in setting value of input fields.
Note: the json object contains keys with spaces like "some key":"some value"
edit:
When I tried Object.keys(data)[index] to access the object field, I got Uncaught TypeError: Object.keys called on non-object
Try This
$("#getDetails").click(function () {
$.get("/servlet", {
mID: 5 })
.success(function (data) {
$("#input1").val(data.d.somekey);
$("#input2").val(data.d.name);
$("#input3").val("directvalue");
});
});
In the comments, you say it's returning this object:
{
"Name": "my name",
"my address": "23,round street",
"Description": "PM Speech at Red Fort on Indep Day 2014"
}
Try:
$("#input2").val(data.Name);
When I did console.out(data), it was printing a json object.
But when I tried Object.keys(data)[index] to access the object field, I got Uncaught TypeError: Object.keys called on non-object.
This means that dataitself was not a json object.
So I got a hint that server was giving a string in which json object was written. I had to simply parse the json object from the data string.
Following is the working code:
$("#getDetails").click(function() {
$.get("/servlet",{
mID : 5
})
.done(function(data) {
var dataObj=JSON.parse(data);
$("#input1").val(dataObj["some key"]);
$("#input2").val(dataObj.name);
});
});

How to get data from json in order to save them in database?

I am beginner in Javascript/jQuery and I am working on an interface made with KnockoutJS, so I have several models. I would like to save all the data in the database but I don't know how to do it.
I started with :
self.save = function() {
var data = ko.toJS(self);
var test = ko.toJSON(self);
console.log(test);
}
$.ajax({
url: "myURL",
data: {'carrier': data.carrier},
type: "POST",
});
and this is the result of the console.log :
{"id":1,"carrier":"1","Settings":[{"id":1,"price":{"id":1,"DeliveryStandard":"3.00","DeliveryExpress":"6.00","Details":{"id":1,"Standard":[{"id":1,"fromPrice":0,"maxPrice":"45.000"}],"Express"[{"id":1,"fromPrice":0,"maxPrice":"66.000"}]}}}}]}
I can get the value of carrier by using data.carrier but I don't know how to get the other data like DeiveryStandard, DeliveryExpress, fromPrice, maxPrice ...
Have you got an idea?
Thanks you in advance, and sorry if my question is silly!
If you format your JSON into a more readable format, with indenting, it makes it a lot easier to understand:
(though it should be noted that it is only technically JSON while in a string format, outside of that it is just a standard javascript object)
{
"id":1,
"carrier":"1",
"Settings":[
{
"id":1,
"price": { "id":1,
"DeliveryStandard":"3.00",
"DeliveryExpress":"6.00",
"Details": { "id":1,
"Standard": [{"id":1,
"fromPrice":0,
"maxPrice":"45.000"
}],
"Express" //Missing semi-colon
[{"id":1,
"fromPrice":0,
"maxPrice":"66.000"
}]
}
}
}}//One too many closing braces
]
}
First thing to note is you have 2 syntax errors, highlighted above with comments. So fix them first! (Though I wonder if they are typos as you seem to have it working at your end)
Then we can look at the structure tree to work out where the values you want are...
DeiveryStandard and DeliveryExpress are both properties of an object assigned to price, which it a property of the first item in the Settings array. So you can access them like so:
var DeliveryStandard = data.Settings[0].price.DeliveryStandard;
var DeliveryExpress= data.Settings[0].price.DeliveryExpress;
fromPrice and maxPrice are found multiple times, in both Standard and Express items. So you need to decide what version you need. If you want Standard then you can get the first item of the Standard array like so:
var standardObject = data.Settings[0].price.Details.Standard[0];
Which you can then access the properties of like:
var fromPrice = standardObject.fromPrice;
var maxPrice = standardObject.maxPrice;
I am sure you can work out how to get the Express version of the same data!
From what you seem to have been able to work out on your own, I think your problem is not knowing how to deal with the arrays. Note that arrays are defined with square brackets [], and elements within an array should be accessed with a zero-based index, for example: array[0] for the first element, and array[1] for the second element.
This should work.
console.log(data.Settings[0].price.DeliveryStandard);
Fixed some errors in your JSON.
var j = {
"id" : 1,
"carrier" : "1",
"Settings" : [{
"id" : 1,
"price" : {
"id" : 1,
"DeliveryStandard" : "3.00",
"DeliveryExpress" : "6.00",
"Details" : {
"id" : 1,
"Standard" : [
{
"id" : 1,
"fromPrice" : 0,
"maxPrice" : "45.000"
}
],
"Express": [
{
"id" : 1,
"fromPrice" : 0,
"maxPrice" : "66.000"
}
]
}
}
}
]
};
alert(j.Settings[0].price.DeliveryStandard);
alert(j.Settings[0].price.DeliveryExpress);
alert(j.Settings[0].price.Details.Standard[0].fromPrice);
alert(j.Settings[0].price.Details.Standard[0].maxPrice);

Categories

Resources