我有一个JSON数据结构,如下所示:
{
"name": "World",
"children": [
{ "name": "US",
"children": [
{ "name": "CA" },
{ "name": "NJ" }
]
},
{ "name": "INDIA",
"children": [
{ "name": "OR" },
{ "name": "TN" },
{ "name": "AP" }
]
}
]
};
我需要更改“名称”中的键名称& “孩子们”说“关键”& “值”。有关如何为此嵌套结构中的每个键名执行此操作的建议吗?
答案 0 :(得分:12)
我不知道为什么你的JSON标记结尾处有一个分号(假设你在问题中代表了什么),但如果删除了,那么你可以使用 reviver function 在解析数据时进行修改。
var parsed = JSON.parse(myJSONData, function(k, v) {
if (k === "name")
this.key = v;
else if (k === "children")
this.value = v;
else
return v;
});
答案 1 :(得分:0)
你可以使用这样的函数:
function clonerename(source) {
if (Object.prototype.toString.call(source) === '[object Array]') {
var clone = [];
for (var i=0; i<source.length; i++) {
clone[i] = goclone(source[i]);
}
return clone;
} else if (typeof(source)=="object") {
var clone = {};
for (var prop in source) {
if (source.hasOwnProperty(prop)) {
var newPropName = prop;
if (prop=='name') newPropName='key';
else if (prop=='children') newPropName='value';
clone[newPropName] = clonerename(source[prop]);
}
}
return clone;
} else {
return source;
}
}
var B = clonerename(A);
请注意,您拥有的不是JSON数据结构(这不作为JSON is a data-exchange format存在),但可能是您从JSON字符串获取的对象。
答案 2 :(得分:0)
试试这个:
function convert(data){
return {
key: data.name,
value: data.children.map(convert);
};
}
或者,如果您需要支持没有地图的旧浏览器:
function convert(data){
var children = [];
for (var i = 0, len = data.children.length; i < len; i++){
children.push(convert(data.children[i]));
}
return {
key: data.name,
value: children
};
}