I would like to create a dynamic JSON array in Javascript like that :
var jsonData = {
"Tasks" : [
{
"__metadata" : {
"uri" : "...",
"type" : "..."
},
"ID" : "...",
"Category" : "..",
// ...
},
{
"__metadata" : {
"uri" : "...",
"type" : "..."
},
"ID" : "...",
"Category" : "..",
// ...
},
// others tasks
], "__count" : "2"
};
I found how to create a JSON in Javascript but not with this syntax. So what is the good way to create the JSON object with the 'Tasks' array and add items in it ?
Thank you for your help
asked Mar 11, 2013 at 9:47
skurty
7391 gold badge11 silver badges26 bronze badges
3 Answers 3
Something like this maybe?
function Metadata(uri,type)
{
this.uri = uri;
this.type = type;
}
function Task(metadata, id, category)
{
this.__metadata = metadata;
this.ID = id;
this.Category = category;
}
var tasks = [new Task(new Metadata('foo','bar'), 1, 'blah'), new Task(new Metadata('foo1', 'bar1'), 2, 'blah2')];
document.write(JSON.stringify({"Tasks": tasks, "__count": tasks.length}));
answered Mar 11, 2013 at 10:03
Srikanth Venugopalan
9,0496 gold badges39 silver badges76 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
Create objects with constructors and use the JSON api.
var jsonData = {};
jsonData.Tasks = new Array();
var Metadata = function(uri, type){
this.uri = uri;
this.type = type;
}
var Task = function (metadata, id, category){
this.__metadata = metadata;
this.ID = id;
this.Category = category;
}
var tasks = jsonData.Tasks;
tasks.push(
new Task(
new Metadata("someUri", "someType"),
1,
"someCategory")
);
jsbin: working example
Comments
I'm using this code and it works :
var jsonData = {};
jsonData.Tasks = [];
var count = 0;
for(...) {
jsonData.Tasks.push({
"__metadata" : {
"uri" : "...",
"type" : "..."
},
"ID" : "...",
"Category" : "...",
});
count++;
}
jsonData.__count = count;
Thank you for your answers and your reactivity !
answered Mar 11, 2013 at 10:12
skurty
7391 gold badge11 silver badges26 bronze badges
1 Comment
Yoeri
I still recommend you use objects rather than string literals. I don't know what it means performance whise, but is a lot less error prone.
lang-js
__countattribute is redundant. It is already stored within theTasksarray.