Parsing a JSON object-within-an-object in javascript - javascript

I have a JSON object that looks like this:
var json = {
"cj-api": {
"products": [
{
"$": {
"total-matched": "231746",
"records-returned": "999",
"page-number": "1"
},
"product": [ {... // contains lots objects with the data I'd like to access } ]
As noted above, I want to access the product array of objects. I can't seem to do this though. I've tried:
console.log(json['cj-api']['products'][0]['product']);
But I get typeError: Cannot read property 'products' of undefined.
What's the correct way to access the array of product (note, singular product, not products). This data is coming from an external source so I can't alter the hyphen in cj-api.
EDIT: Here's what the raw console log of json looks like:
{"cj-api":{"products":[{"$":{"total-matched":"231746","records-returned":"999","page-number":"1"},"product":[{ << lots of data in here>>
EDIT 2: To further clarify, I got this object by running JSON.stringify(result) after I put some XML into XML2js.

i have tried the following JSON structure:
var json = {
"cj-api": {
"products": [
{
"$": {
"total-matched": "231746",
"records-returned": "999",
"page-number": "1"
},
"product": [
{
"a": "a",
"b": "b",
"c": "c"
}
]
}
]
}
};
with the log statement as:
console.log(json['cj-api']['products'][0]['product']);
And result is as follows:
[Object { a="a", b="b", c="c"}]

Well your way of accessing json is absolutely correct. This is for debugging. Try
console.log(json['cj-api']);
console.log(json['cj-api']['products']);
console.log(json['cj-api']['products'][0]);
console.log(json['cj-api']['products'][0]['product']);
Which ever line returns undefined means your json is broken there.
If this doesn't work then you need to check for other similar keys. Maybe they value you are trying to find is actually undefined.
Maybe you are trying to loop. If you are then check for the condition if (JSONStructure[key]==undefined) console.log("Undefined at position ..."). That is the only way if you have valid JSON.

typeError: Cannot read property 'products' of undefined means that json exists, but json['cj-api'] is undefined. If you are sure that you are using the right variable name, I think this might be a scope issue, where you are using an other variable than you intend to. json might be the json string, instead of the array-like object. Try renaming your variable and see if you still get this problem. Otherwise the string is not automatically parsed for you and you'll have to parse it with JSON.parse( ... ).
Edit:
var json = '{ "me": "be an evil string" }';
console.log( json ); //'{ "me": "be an evil string" }'
console.log( json['me'] ); //undefined
console.log( JSON.parse( json )['me'] ); // 'be an evil string'

Since your question is missing the last
}
]
}
}
and others here changed your example and made it work, did you try to correct it?
If not then I suggest you or the dataprovider correct the structure of the reply.

I have tried below json structure
var json={
"cj-api": {
"products": [
{
"$": {
"total-matched": "231746",
"records-returned": "999",
"page-number": "1"
},
"product": []
}
]
}
}
now json['cj-api']['products'][0]['product'] will work

Related

How to parse an string into more workable key-values?

So I have the following response:
{
"errors": [
{
"errorKey": "ERROR_NO_DELIVERY_OPTIONS",
"errorParameters": "[{\"errorMessage\":\"ERROR_DELIVERY_OPTIONS_YOU_SELECTED_NOT_AVAILABLE_NOW\",\"partNumbers\":[\"19308033\",\"19114798\"]},{\"errorMessage\":\"Pickup At Seller not available for these orderItemIds\",\"orderItemIds\":[\"10315031\",\"10315032\"],\"availableShipModeId\":\"13201\"}]",
"errorMessage": "ERROR_NO_DELIVERY_OPTIONS",
"errorCode": "ERROR_NO_DELIVERY_OPTIONS"
}
]
}
Unfortunately, I'm not sure how to work with the value of "errorParameters" since it just a string and not a simple key-value like the others. How would I extract all the information so I can work with it. A co-woker mentioned parsing it but not sure what he meant by that and how. Below is a more readable value. I'm working with javascript.
[
{
"errorMessage": "ERROR_DELIVERY_OPTIONS_YOU_SELECTED_NOT_AVAILABLE_NOW",
"partNumbers":
[
19308033,
19114798
]
},
{
"errorMessage": "No Shipmodes Available for these orderItemsIds",
"orderItemIds": [
10315031,
10315032
]
}
]
You will need to use JSON.parse to transform JSON strings into a JS Object.
You'll need to do this in your code. I.E.
data.errors.forEach(e => console.log(JSON.parse(e.errorParameters)))
You can use just JSON.parse() function, which changes string JSON representation into a JavaScript object.
const parsedErrorParameters = JSON.parse(data.errorParameters);
console.log(parsedErrorParameters[0].errorMessage); // ERROR_DELIVERY_OPTIONS_YOU_SELECTED_NOT_AVAILABLE_NOW
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse

Getting values of json array in Mocha JS

I have following issue, this json is returned by api:
"products": {
"10432471": {
"id": 10432471
},
"10432481": {
"id": 10432481
}
}
and I need to get names of all variables under products array, how to get them?
That values are constantly changing everyday, so I can not refer to their names
Trying console.log(res.body.menu.categories[i].products.values()); but its not worked.
Any sugesstion how can I get 10432471 and 10432481 from products? Without referring to variable names.
You are able to get that via Object.keys(res.body.menu.categories[i].products)
To get the object properties, the shortest is using Object.keys()
var obj = {"products": {
"10432471": {
"id": 10432471
},
"10432481": {
"id": 10432481
}
}}
var properties = Object.keys(obj.products)
console.log(properties)

Remove the parent element from JSON reply

I have a route used for AJAX calls. It gets items from a DB and returns a JSON array.
I'm using:
return reply({
myArray
}).code(200);
Everything works but my output in the browser is:
{
"myArray":[
{
"_id":"1",
"name":"Asd1"
},
{
"_id":"2",
"name":"Asd2"
}
}
But what I need is:
{
[
{
"_id":"1",
"name":"Asd1"
},
{
"_id":"2",
"name":"Asd2"
}
]
}
Very basically, I need to get rid the "myArray" parent element and leave just the array there. It looks like a simple task but I can't find documentation or samples anywhere.
Thanks,
Marco
This:
{
[
{
"_id":"1",
"name":"Asd1"
},
{
"_id":"2",
"name":"Asd2"
}
]
}
is invalid JSON notation. Within curly braces, you should have key-value pairs where keys are strings and values are valid JSON values (strings, numbers, booleans, null, arrays, or objects).
Perhaps what you expect is just the array:
[
{
"_id":"1",
"name":"Asd1"
},
{
"_id":"2",
"name":"Asd2"
}
]
which is valid JSON. In this case, you may simply send it to your reply function:
return reply(myArray).code(200);
For more info on JSON notation, see the article on MDN and play with JSON.stringify to develop better intuition on when the JSON you see is valid or not.

Using 'this' keyword in JavaScript object

I like to think I understand JavaScript, but I found something unexpected today and I was hoping someone could explain to me why it happens.
Take this code
var animalData = {
cow:"cow",
sheep:"sheep",
getCow:function()
{
return this.cow;
},
animalList:[
{
animalId:this.cow,
label:"This is a cow"
},
{
animalId:this.sheep,
label:"This is a sheep"
}
]
};
console.log(animalData.getCow());
console.log(JSON.stringify(animalData.animalList,null," "))
The output is not what I was expecting. Calling animalData.getCow() results in "cow" just as you would expect. But it's what gets return by the second console.log that confuses me.
[
{
"label": "This is a cow"
},
{
"label": "This is a sheep"
}
]
In other words, the object removes the animalId property entirely from the objects defined. I was expecting this
[
{
"animalId":"cow",
"label": "This is a cow"
},
{
"animalId":"sheep",
"label": "This is a sheep"
}
]
And I could understand maybe this
[
{
"animalId":undefined,
"label": "This is a cow"
},
{
"animalId":undefined,
"label": "This is a sheep"
}
]
But why does the animalId property get removed entirely?
Can anyone explain what's going on under the surface to cause this behaviour? I'm guessing that the this keyword does not work because the properties are undefined when it is invoked, but why does it remove the property entirely?
NB: I'm not looking for a workaround, that's easy enough to do - just interested in why it happens.
JSFiddle here
At the point the object is initialised, this refers to the outer context, which won't have cow and sheep properties. As you thought, that will result in the animalIds being undefined.
JSON.stringify does certain things with undefined properties, namely:
If undefined, a function, or a symbol is encountered during conversion it is either omitted (when it is found in an object) or censored to null (when it is found in an array).
Which is why you don't see them.
First of all, you are correct your last example, this is what you are trying to stringify:
[
{
"animalId":undefined,
"label": "This is a cow"
},
{
"animalId":undefined,
"label": "This is a sheep"
}
]
And, because those values are undefined JSON.stringify simply omits them.
Why the values above are undefined is because the this keyword in this.cow refers to the current scope, which is actually the window Object as it is not inside any other function.
Why it makes sense to omit keys with undefined values? Because whether they exist or not, if you try to access object.key you will get the correct value: undefined

JavaScript Json Array Parsing using Backbone

I have the following sample json:
{
"camp": [
{
"name": "Name",
"data": [
{
"date": "04/08/2014",
"value": 1000
},
{
"date": "05/08/2014",
"value": 1110
}
]
}
]
}
Here, I'm able to do: model.get("camp")[0], but when I try: model.get("camp")[0].get("data"), I get the following error:
undefined is not a function
Here model is the standard backbone model which extends Backbone.Model
I'm confused what I'm doing wrong !!
You only need to call the model.get() function once. After that, you can treat the returned object just like any other javascript-object. For example, you could do this to get one of the values deep inside the object:
model.get("camp")[0].data[0].value
To achieve what you are trying to get, do this:
model.get("camp")[0].data
If you want to acces a property of your json array, you should simply do like this:
var test = json.camp.name
This is how you get your value:
obj.camp[0].data[0]

Categories

Resources