给定没有索引的JSON数据:
var knol = [
{"hant":"火","status":1,"rank":30,"score": 1},
{"hant":"人","status":1,"rank":33,"score": 2},
{"hant":"山","status":1,"rank":60,"score": 5},
{"hant":"是","status":1,"rank":50,"score": 3}
];
给定JS函数以使用索引重新创建数据:
var addIndex = function(object, key1, key2){
var data = object;
var newData = "[";
for (var i in data) {
if (!key2) {
var newIndex = data[i][key1]
} else {
var newIndex = data[i][key1] + data[i][key2]
}
newData = newData + "\"" + newIndex + "\":" + JSON.stringify(data[i]) +",";
}
newData = newData.concat("]").replace(",]", "]");
console.log(newData);
newData = JSON.parse(newData);
return newData;
};
knol = addIndex(knol, "hant");
我收到错误"Uncaught SyntaxError: Unexpected token :"
,而代码中指定位置没有“:”。这似乎会破坏我的大脚本。知道发生了什么事吗?
答案 0 :(得分:2)
中间JSON不正确,因此最终JSON.parse
失败。中间文本是["火":{"hant":"火",..
,如控制台上所报告的那样,它确实不正确,因为数组没有键。
只需构建/重建整个对象图作为JS对象,然后在其上使用JSON.stringify
- 或者,在这种情况下,永远不会,因为最终结果将是无论如何JS对象!
var addIndex = function(data, key1, key2){
var newData = {}; // new JS object - there is /no/ JSON here.
var newIndex;
for(var i in data){
if(!key2){
newIndex = data[i][key1];
}else{
newIndex = data[i][key1] + data[i][key2];
}
// add data to new object with appropriate property/key
// and do NOT manually build JSON text.
newData[newIndex] = data[i];
}
// return object directly; it's not JSON text, no need to parse it!
return newData;
};
答案 1 :(得分:1)
您需要创建一个对象({…}
),而不是数组([…]
)。这可行:
var newData = "{";
for(var i in data){
if(!key2){ var newIndex = data[i][key1] }else{ var newIndex = data[i][key1]+ data[i][key2]}
newData = newData + "\""+newIndex+"\":"+JSON.stringify(data[i])+",";
}
newData = newData.concat("}").replace(",]", "]").replace(",}", "}");
但是,我强烈建议直接操作数据而不是尝试从其各个部分手动构造JSON字符串。
这是一个简单的实现:
var addIndex = function(object, key1, key2){
var data = object, newData = {}, newIndex;
for(var i in data){
if(!key2){
newIndex = data[i][key1];
}else{
newIndex = data[i][key1]+ data[i][key2];
}
newData[newIndex] = data[i];
}
console.log(newData);
return newData;
};