如何转换为json对象

时间:2014-01-02 13:38:16

标签: javascript d3.js

我正在尝试以这种格式创建json:

[
{
"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]]
}
]

我有以下代码:

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) );

但是我按以下格式获取数据:

{"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"}}

我想将签到详情放在大括号中,如上所示。我在这里缺少什么?

3 个答案:

答案 0 :(得分:1)

请试试这个

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) );

http://jsfiddle.net/SdLWR/

答案 1 :(得分:0)

你已经签入了一个对象,而是在数组中生成并按下这样推送值:

var checkins = [];
checkins.push(200);
checkins.push(100);

或者像这样:

var checkins = [200,100];

答案 2 :(得分:0)

您正在创建对象而不是数组,所以这样做:

var checkins = [ 200, 100, 200, 300, 100, 50, 80, 60, 50, 40, 30, 200 ];

请使用有关Java脚本语言及其数据类型的高可用文档,例如:object,array等:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array