This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 4 years ago.
I am getting below sample json data as input,
var JSONDATA =
{
"MainNode": {
"_attributes": {
"class": "ABC",
"projectclass": "MyProject",
"prjname": "PrjName",
"enabled":"true"
},
"PrjProp": {
"_attributes": {
"name": "MyProject.save"
},
"_text": true
}
}
}
Using Jquery or Javascript, I want to get the "projectclass" value in first "_attributes". There could be multiple "_attributes" in JSON object but the requirement to the "projectclass" (fixed) from the first (fixed) "_attributes" only.
This can be achieved like,
console.log(JSONDATA.MainNode._attributes.testclass);
but "MainNode" is not fixed, this can be "OtherNode". So how to handle this is variable ? I tried , console.log(Object.keys($scope.testplan)[0]); which shows main node name but how to use this in console.log(JSONDATA.MainNode._attributes.testclass); as variable ?
Please suggest.
Thanks
You have to access as JSONDATA.MyProject._attributes.projectclass
Using [0] is accessing the first element of an array. This is an object, so that is the reason why you are not able to access JSONDATA[0][0].projectclass
var JSONDATA = {"MyProject":{"_attributes":{"class":"ABC","projectclass":"MyProject","prjname":"PrjName","enabled":"true"},"PrjProp":{"_attributes":{"name":"MyProject.save"},"_text":true}}};
console.log( JSONDATA.MyProject._attributes.projectclass );
And there is going to be only 1 _attributes under MyProject.
If you have multiple projects, You can loop by:
var JSONDATA = {
"MyProject":{"_attributes":{"class":"ABC","projectclass":"MyProject","prjname":"PrjName","enabled":"true"},"PrjProp":{"_attributes":{"name":"MyProject.save"},"_text":true}},
"MyOtherProject":{"_attributes":{"class":"ABC","projectclass":"MyOtherProject","prjname":"PrjName","enabled":"true"},"PrjProp":{"_attributes":{"name":"MyProject.save"},"_text":true}}
};
for ( var key in JSONDATA ) {
console.log( JSONDATA[key]._attributes.projectclass );
}
you cant use JSONDATA[0][0] to acces a JSON object
for example data is your JSON object to access projectclass simply
data={
"MyProject": {
"_attributes": {
"class": "ABC",
"projectclass": "MyProject",
"prjname": "PrjName",
"enabled": "true"
},
"PrjProp": {
"_attributes": {
"name": "MyProject.save"
},
"_text": true
}
}
}
console.log(data.MyProject._attributes.projectclass);
Related
This question already has answers here:
How to set object property (of object property of..) given its string name in JavaScript?
(16 answers)
Closed 3 years ago.
I have a use case where i will initially have a JSON object with few elements and I want to add few more new elements to this object using JSON path with the help of Javascript.
Eg:
JSON object:
{
"article": {
"title": "Article Title",
"sect1": {
"title": "Section1 Title",
"para": "Text"
}
}
}
I would like to set 'article.sect1.subsection.subtitle' as 'Test Title' and 'article.sect1.subsection.para' as 'Number'.
Could you please suggest any solution?
I could add element inside existing section as below
JSONObject.article.sect1.sect1.newElement = 'newelementvalue';
But this is not working for above scenario.
You can easily convert the string to a JSON object and then manipulate it as you would normally. Once you are done, stringify it back and you can persist it how you wish.
const json = `{ "article": { "title": "Article Title", "sect1": { "title": "Section1 Title", "para": "Text" } } }`;
const obj = JSON.parse(json);
obj.article.sect1.subtitle = 'Test Title';
obj.article.sect1.subsection = {para: 'Number'};
const str = JSON.stringify(obj);
console.log(str)
I want to add a new object for each nested array. I'm calling this function any time I add a product to my orderintake:
add2order(productID, productName, productRatePlans) {
this.orderIntake.push({ productID, productName, productRatePlans });
let i = 0;
this.orderIntake[0].productRatePlans[0].productRatePlanCharges.forEach(element => {
i++;
this.orderIntake[0].productRatePlans[0].productRatePlanCharges[
i
].quantity = this.orderIntake[0].productRatePlans[0].productRatePlanCharges[
i
].defaultQuantity;
});
}
this is an example response from the server:
{
"id": "8adc8f996928b9a4016929c59b943a8f",
"sku": "SKU-00006778",
"Partner_Account_ID__c": null,
"productRatePlans": [
{
"id": "8adce4216928c28d016929c59bff3372",
"status": "Active",
"name": "Enterprise",
"description": null,
"effectiveStartDate": "2016-02-26",
"effectiveEndDate": "2029-02-26",
"productRatePlanCharges": [
{
"id": "8adc8f996928b9a4016929c59d183a92",
"name": "USAGE_COUNTER_2",
"type": "Usage",
"model": "Volume",
"uom": "Each",
"pricingSummary": [
"Up to 5000 Each: USD0 flat fee"
],
"pricing": [
{
...
}
],
"defaultQuantity": null,
"applyDiscountTo": null,
"discountLevel": null,
"discountClass": null,
...
"financeInformation": {
..,
}
}
]
}
],
"productFeatures": [
{
...
}
]
}
The data is being retrived this way from an external REST backend so unfortunately I can't initialize the data including the new property...
so in every productRatePlanCharges there should be 1 new object 'quantity'.
How can I add this field to every productRatePlanCharges?
Right now I'm getting: ERROR
TypeError: Cannot read property 'productRatePlanCharges' of undefined
And how can I make sure I'm always adding this to the last orderIntake element? Don't mind productRatePlans there is only 1 in each orderintake...
thanks for your support!
Here you have to create productDetails object with inititalised array like below so that you won't get the error.
add2order(productID, productName, productRatePlans) {
// Create object like below
let productDetails = { productID : productID, productName : productName, productRatePlans : productRatePlans
}
this.orderIntake.push(productDetails);
let i = 0;
this.orderIntake[0].productRatePlans[0].productRatePlanCharges.forEach(element => {
i++;
this.orderIntake[0].productRatePlans[0].productRatePlanCharges[
i
].quantity = this.orderIntake[0].productRatePlans[0].productRatePlanCharges[
i
].defaultQuantity;
});
}
Hope this will help!
as you used Angular you probably use Typescript too. I recommend that you create a model like your incoming model and there define your quantity: number inside productRatePlanCharges object. then map the incoming data to your own model. therefore you will have a quantity=0 in your model that you can change it later in a loop.
If you want to continue with your own way take a look at this:
Add new attribute (element) to JSON object using JavaScript
there is no problem to add an element to current model almost like you did, and the problem might be somewhere else as your error refers to existence of productRatePlanCharges!
as you used forEach I prefer to use that 'element' and double iterating with i++; is not a good idea to me.
this might be better:
element.quantity = element.defaultQuantity;
Have got a json file exported from mysql. One particular line is not a well represented json object, i'm trying to convert this to a proper array of object.
var data = "{"54":
{"ID":"54",
"QTY":"1",
"NAME":"Large",
"TOTAL":1.86
},
"TOTAL":10.54,
"313":
{"ID":"313",
"QTY":2,
"NAME":"Quater Pounder",
"TOTAL":8.68
}
}"
//and wants to make it:
var data = [
{"ID" : "54",
"QTY" : "1",
"NAME": "Quarter Pounder",
"TOTAL": 8.68
},
{"ID":"313",
"QTY":2,
"NAME": "Quater Pounder",
"TOTAL":8.68
}
]
I was able to fix this by using angular.forEach(response, function(item){}), I then created a childArray, which I pushed the result of the above into.
Please see code:
angular.forEach( $scope.response, function (item) {
item.childrenList = [];
angular.forEach( JSON.parse( item.details ), function (value, id) {
item.childrenList.push( value );
})
});
I have a json url that returns data in the format
{
"photos" : [
{
"id": 1, "image":"https://path/to/my/image/1.jpg"
},
{
"id": 2, "image":"https://path/to/my/image/2.jpg"
}
]
}
I'm using the json in a javascript function, and need to manipulate it to remove the root key. i.e. I want something that looks like
[
{
"id": 1, "image":"https://path/to/my/image/1.jpg"
},
{
"id": 2, "image":"https://path/to/my/image/2.jpg"
}
]
I've been hacking around with various approaches, and have referred to several similar posts on SO, but nothing seems to work. The following seems like it should.
var url = 'http://path/to/my/json/feed.json';
var jsonSource = $.getJSON( url );
var jsonParsed = $.parseJSON(jsonSource);
var jsonFeed = jsonParsed.photos
What am I doing wrong?
A couple of issues there.
That's invalid JSON, in two different ways. A) The : after "photos" means that it's a property initializer, but it's inside an array ([...]) when it should be inside an object ({...}). B) There are extra " characters in front of the images keys. So the first thing is to fix that.
You're trying to use the return value of $.getJSON as though it were a string containing the JSON text. But $.getJSON returns a jqXHR object. You need to give it a success callback. That callback will be called with an object graph, the JSON is automatically parsed for you.
Assuming the JSON is fixed to look like this:
{
"photos": [
{
"id": 1,
"image": "https://path/to/my/image/1.jpg"
},
{
"id": 2,
"image": "https://path/to/my/image/2.jpg"
}
]
}
Then:
$.getJSON(url, function(data) {
var photos = data.photos;
// `photos` now refers to the array of photos
});
My mobile app reads an external json object. How can I check in javascript that a key node exists in the dynamically generated json structure? I tried the hasOwnProperty or containsKey methods, but without luck.
Example json data:
{ "element1":
{ "element2": { "Number": "0" },
"element3": { "Number": "1" },
"element4": { "Number": "2" }
}
}
As these elements are generated dynamically, I want to check if the key element3 exists in this structure. No luck with data.element1.hasOwnProperty("element3").
Yes, hasOwnProperty() method does not work for a Json object. It works for a Java Script Object. So You just need to convert this Json object into a Java Script Object using eval() method and check inside that object.
When you convert above Json structure, it will create an Object (element1) inside another Object (say JSObject). element1 will contain properties element2, element3 and element4. So your code should go like this.
var MyObject={ "element1":
{ "element2": { "Number": "0" },
"element3": { "Number": "1" },
"element4": { "Number": "2" }
}
}
var JSObject=eval('(' + MyObject+ ')');
var IsExistElement3 = JSObject.element1.hasOwnProperty("element3");