我正在使用highchart插件开发图表。为图表提供动态输入。所以,我需要将JSON格式更改为Array。如何使用javascript将JSON数组对象格式更改为Array?
[
{
"scoreCount": "108",
"legendDesc": "Excellent ",
"colorPatchCode": "#009900"
},
{
"scoreCount": "20",
"legendDesc": "Fail ",
"colorPatchCode": "#FF0000"
}
]
转换数组格式,如
[
[
"scoreCount": "108",
"legendDesc": "Excellent ",
"colorPatchCode": "#009900"
],
[
"scoreCount": "20",
"legendDesc": "Fail ",
"colorPatchCode": "#FF0000"
]
]
任何人都可以帮忙吗?
答案 0 :(得分:4)
[
"scoreCount": "108",
"legendDesc": "Excellent ",
"colorPatchCode": "#009900"
],
是无效的结构。 数组可以包含单个元素。本机或包含其他项(属性)或数组的对象。
答案 1 :(得分:1)
如果尝试这样做:
var arr = [
{
"scoreCount": "108",
"legendDesc": "Excellent ",
"colorPatchCode": "#009900"
},
{
"scoreCount": "62",
"legendDesc": "Good ",
"colorPatchCode": "#99CC00"
},
{
"scoreCount": "55",
"legendDesc": "Acceptable ",
"colorPatchCode": "#FFFF00"
},
{
"scoreCount": "31",
"legendDesc": "Poor ",
"colorPatchCode": "#FF9900"
},
{
"scoreCount": "20",
"legendDesc": "Fail ",
"colorPatchCode": "#FF0000"
}
];
for (i = 0;i<arr.length;i++) {
var a = [];
for (n in arr[i]) {
a[n] = arr[i][n];
}
arr[i] = a;
}
for (i = 0;i<arr.length;i++) {
alert(arr[i]['scoreCount']);
}
答案 2 :(得分:0)
var source = [
{
"scoreCount": "108",
"legendDesc": "Excellent ",
"colorPatchCode": "#009900"
},
{
"scoreCount": "62",
"legendDesc": "Good ",
"colorPatchCode": "#99CC00"
},
{
"scoreCount": "55",
"legendDesc": "Acceptable ",
"colorPatchCode": "#FFFF00"
},
{
"scoreCount": "31",
"legendDesc": "Poor ",
"colorPatchCode": "#FF9900"
},
{
"scoreCount": "20",
"legendDesc": "Fail ",
"colorPatchCode": "#FF0000"
}
];
var out = [];
for (var i = 0; i < source.length; i++) {
var tmp = [];
for (var i2 in source[i]) {
tmp.push(source[i][i2]);
}
out.push(tmp);
}
out将是:
[
["108","Excellent ","#009900"],
["62","Good ","#99CC00"],
["55","Acceptable ","#FFFF00"],
["31","Poor ","#FF9900"],
["20","Fail ","#FF0000"]
]
正如其他人已经说过的那样..你不能在javascript数组中存储键值。这就是json的用途。
答案 3 :(得分:0)
虽然语法错误,但是如果你想要的话,你仍然可以制作这种格式的字符串。
但是,正如您所知,您无法将其读回JavaScript变量。
答案 4 :(得分:0)
您可以使用javascript的面向对象功能以更清晰的方式实现此目的。
var jsonArray = [
{
"scoreCount": "108",
"legendDesc": "Excellent ",
"colorPatchCode": "#009900"
},
{
"scoreCount": "62",
"legendDesc": "Good ",
"colorPatchCode": "#99CC00"
},
{
"scoreCount": "55",
"legendDesc": "Acceptable ",
"colorPatchCode": "#FFFF00"
},
{
"scoreCount": "31",
"legendDesc": "Poor ",
"colorPatchCode": "#FF9900"
},
{
"scoreCount": "20",
"legendDesc": "Fail ",
"colorPatchCode": "#FF0000"
}
];
function MyJsObject(scoreCount, legendDesc, colorPatchCode) {
this.scoreCount = scoreCount;
this.legendDesc = legendDesc;
this.colorPatchCode = colorPatchCode;
}
function createJSArray() {
var jsArray = new Array();
for(i = 0; i < jsonArray.length; i++) {
var m = new MyJsObject(jsonArray[i].scoreCount, jsonArray[i].legendDesc, jsonArray[i].colorPatchCode);
jsArray[i] = m;
}
alert(jsArray[4].scoreCount);//access any object like this
}