如何更改JSON的节点名称?

时间:2013-05-20 20:22:33

标签: javascript jquery json

如何更改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值。

4 个答案:

答案 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'));

虽然我认为没有任何实际需要更换钥匙。