繁体   English   中英

在嵌套的JSON结构中更改密钥名称

[英]Change key name in nested JSON structure

我有一个JSON数据结构,如下所示:

{
    "name": "World",
    "children": [
      { "name": "US",
          "children": [
           { "name": "CA" },
           { "name": "NJ" }
         ]
      },
      { "name": "INDIA",
          "children": [
          { "name": "OR" },
          { "name": "TN" },
          { "name": "AP" }
         ]
      }
 ]
};

我需要将键名从“name”和“children”更改为“key”和“value”。 有关如何为此嵌套结构中的每个键名执行此操作的任何建议?

我不知道你为什么在你的JSON标记结尾处有一个分号(假设你在问题中表示的是) ,但是如果删除它,那么你可以使用reviver函数在解析数据时进行修改。

var parsed = JSON.parse(myJSONData, function(k, v) {
    if (k === "name") 
        this.key = v;
    else if (k === "children")
        this.value = v;
    else
        return v;
});

演示: http //jsfiddle.net/BeSad/

你可以使用这样的函数:

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是数据交换格式,因此不存在),但可能是您从JSON字符串获取的对象。

试试这个:

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
  };
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM