0

如何更改 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节点是 my 的值var childType = "view"。我怎样才能改变这个?

PS:我有多个childType值。

4

4 回答 4

0

改变这个

childType:{

view:{
于 2013-05-20T20:24:32.533 回答
0

代替

child=[];
child[childTipy]= { 
            childType:{
                "tipo": childTipy,
                "nome":childName,
            }
        };

child=[];
child[childTipy]= {};
child[childTipy][childType] = {
                "tipo": childTipy,
                "nome":childName,
            };
于 2013-05-20T20:38:16.887 回答
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

于 2013-05-20T20:38:24.523 回答
-1

如果childType仅出现在键中:

var someJson = '{"windows":[{"window":{"nome":"Win2","title":"Win","childrens":[{"childType":{"tipo":"view","nome":"view0"}}]}}]}';

var newJson = $.parseJSON(someJson.replace('childType', 'view'));

尽管我认为没有任何实际需要更改密钥。

于 2013-05-20T20:34:23.413 回答