I am trying to construct JSON object in js. There are couple of posts already about this topic in stack overflow itself. Referred to How do i build JSON dynamically in javascript?. Have to construct JSON exactly something like mentioned in the post.
{
"privilege": {
"accesstype": "VIEW",
"attribute": [
{
"code": "contenttype",
"displayname": "Content type",
"value": {
"valcode": "book_article",
"valdisplayName": "Book Article"
}
},
{
"code": "mime",
"displayname": "Mime type",
"value": {
"valcode": "xml",
"valdisplayName": "Xml"
}
}
]
}
}
Follwed the answers in the post and tried this,
var privilege = {};
privilege.attribute[0].code = "contenttype";
privilege.attribute[0].displayname = "Content type";
privilege.attribute[0].value.valcode = "book_article";
privilege.attribute[0].value.valdisplayName = "Book Article";
But getting error as privilege.attribute undefined.
I am not able to figure out where I am going wrong. Assuming there must be some declaration problems. Any light on it would be of great help.
privilege.attribute = new Array()or something like that before adding the members to it? I think it has to do with the fact thatattributeitself is not being declared and you're immediately trying to use it as an array. Just a guess though.privilege.attributeas an array and the first element of that array as an object. Please have a look at developer.mozilla.org/en-US/docs/JavaScript/Guide/…. Once you built the object, you can useJSON.stringifyto convert it to JSON.