I am trying to create json in this format:
[
{
"name":"aaa_aaaurf",
"region":"F&R",
"checkins":[[1,0],[2,0],[3,0],[4,3],[5,0],[6,0],[7,0],[8,3],[9,0],[10,0],[11,0],[12,0]]
}
]
I have the following code:
var checkins = {};
checkins["1"] = "200";
checkins["2"] = "100";
checkins["3"] = "200";
checkins["4"] = "300";
checkins["5"] = "100";
checkins["6"] = "50";
checkins["7"] = "80";
checkins["8"] = "60";
checkins["9"] = "50";
checkins["10"] = "40";
checkins["11"] = "30";
checkins["12"] = "200";
var display2 = {};
display2["name"] = "aaa_ct";
display2["region"] = "F&R";
display2["checkins"] = checkins;
console.log( JSON.stringify(display2) );
However i am getting the data in the following format:
{"name":"aaa_ct",
"region":"F&R",
"checkins":{"1":"200","2":"100","3":"200","4":"300","5":"100","6":"50","7":"80","8":"60","9":"50","10":"40","11":"30","12":"200"}}
I would like to enclose the checkins details in the braces as shown above. What am i missing here?
Please try this
var checkins = {};
checkins["1"] = "200";
checkins["2"] = "100";
checkins["3"] = "200";
checkins["4"] = "300";
checkins["5"] = "100";
checkins["6"] = "50";
checkins["7"] = "80";
checkins["8"] = "60";
checkins["9"] = "50";
checkins["10"] = "40";
checkins["11"] = "30";
checkins["12"] = "200";
var checkins2 = [];
for(var i in checkins) checkins2.push([i, checkins[i]]);
var display2 = {};
display2["name"] = "aaa_ct";
display2["region"] = "F&R";
display2["checkins"] = checkins2;
console.log( JSON.stringify(display2) );
You've made checkins into an object, make in an array instead and push the values in either like this:
var checkins = [];
checkins.push(200);
checkins.push(100);
or like this:
var checkins = [200,100];
You are creating object instead of array, so do that way:
var checkins = [ 200, 100, 200, 300, 100, 50, 80, 60, 50, 40, 30, 200 ];
And please, use highly available documentation on Java-Script language and its data types like: object, array, etc: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.