如何更改JSON中节点的名称?
我的代码:
childType = view
childName = view0
child=[];
child[childTipy]= {
childType:{
"tipo": childTipy,
"nome":childName,
}
};
childList.push(child[childTipy]);
minhasWindows = {"window": {
"nome": "Win2",
"title": "Win",
"childrens": childList
}
};
结果JSON:
{
"windows" : [
{
"window" : {
"nome" : "Win2",
"title" : "Win",
"childrens" : [
{
"childType" : {
"tipo" : "view",
"nome" : "view0"
}
}
]
}
}
]
}
我希望childType
节点是我var childType = "view"
的值。我怎么能改变这个?
PS:我有多个childType
值。
答案 0 :(得分:0)
更改此
childType:{
到
view:{
答案 1 :(得分:0)
替换
child=[];
child[childTipy]= {
childType:{
"tipo": childTipy,
"nome":childName,
}
};
与
child=[];
child[childTipy]= {};
child[childTipy][childType] = {
"tipo": childTipy,
"nome":childName,
};
答案 2 :(得分:0)
如果希望属性来自变量,请使用数组语法分配属性。
var childType = "view"; // String needs to be quoted
var childName = "view0"; // String needs to be quoted
var child = {}; // This must be an object, not array
child[childType] = {
tipo: childType, // Don't need to quote keys in object literals
nome: childName,
};
childList.push(child);
您的child
对象中也有太多级别。
答案 3 :(得分:-1)
如果仅在密钥中显示childType
:
var someJson = '{"windows":[{"window":{"nome":"Win2","title":"Win","childrens":[{"childType":{"tipo":"view","nome":"view0"}}]}}]}';
var newJson = $.parseJSON(someJson.replace('childType', 'view'));
虽然我认为没有任何实际需要更换钥匙。