"嵌套" JSON to" unnested" Javascript中的JSON

时间:2015-07-28 15:09:15

标签: javascript json nested

我正在尝试将我从API获得的JSON转换为Javascript中相同JSON的不同形式。 我的JSON有会员,很多父母' (嵌套对象)和许多子对象(嵌套的对象数组)。我很想成为父母的成员。

我的JSON示例如下:

[
  {
    "street": [
      {
        "addressinfo": {
          "id": 110,
          "description": "Bezoekaddress"
        },
        "id": 1,
        "name": "Hoogveldstraat"
      }
    ],
    "id": 1,
    "searchName": "JacksIcecream",
    "chamberOfCommerce": ""
  },
  {
    "street": [],
    "id": 2,
    "searchName": "OAK",
    "chamberOfCommerce": ""
  }
]

我正在尝试将其转换为以下内容:

 [
   {
    "street": [
      {
        "addressinfo_id": 110,
        "addressinfo_description": "Bezoekaddress",
        "id": 1,
        "name": "Hoogveldstraat"
      }
    ],
    "id": 1,
    "searchName": "JacksIcecream",
    "chamberOfCommerce": ""
  },
  {
    "street": [],
    "id": 2,
    "searchName": "OAK",
    "chamberOfCommerce": ""
  }
]

我现在已经坚持了一段时间,而且我真的找不到这个问题的任何答案,我能找到的所有问题都是关于扁平阵列,而我只是想把它弄平。非阵列嵌套对象&#39 ;.我怎么能这样做?

3 个答案:

答案 0 :(得分:0)

function parseObject(obj) {
    var i, path, x, type = ({}).toString.call(obj);
    if (type == "[object Array]") {
        for (i = 0; i < obj.length; i++) {
            parseObject(obj[i]);
        }
    }
    else if (type == "[object Object]") {
        path = (arguments[1] && arguments[1].length) ? arguments[1] + "_" : "";
        for(i in obj) {
            if (obj.hasOwnProperty(i)) {
                x = obj[i];
                if (path.length) {
                    delete obj[i];
                    obj[path + i] = x;
                }
                parseObject(x, path + i);
            }
        }
    }
}

tested as follows:

var x = [{
    "street": [{
        "addressinfo": {
            "id": 110,
            "description": "Bezoekaddress"
        },
        "id": 1,
        "name": "Hoogveldstraat"
    }],
    "id": 1,
    "searchName": "JacksIcecream",
    "chamberOfCommerce": ""
}, {
    "street": [],
    "id": 2,
    "searchName": "OAK",
    "chamberOfCommerce": ""
}];
parseObject(x);
console.log(JSON.stringify(x));

Output (run through http://jsbeautifier.org/ ):

[{
    "street": [{
        "addressinfo": {
            "addressinfo_id": 110,
            "addressinfo_description": "Bezoekaddress"
        },
        "id": 1,
        "name": "Hoogveldstraat"
    }],
    "id": 1,
    "searchName": "JacksIcecream",
    "chamberOfCommerce": ""
}, {
    "street": [],
    "id": 2,
    "searchName": "OAK",
    "chamberOfCommerce": ""
}]

答案 1 :(得分:0)

遍历顶级数组中的元素,在每个元素中找到street数组,并遍历其成员并操纵其内容:

json . forEach(function(elt) {
  elt.street . forEach(function(street) {
    street.addressinfo_id = street.addressinfo.id;
    street.addressinfo_desc = street.addressinfo.desc;
    delete street.addressinfo;
  });
});

或者你在寻找更通用和可参数化的东西吗?

答案 2 :(得分:-1)

检查出来

&#13;
&#13;
// Convert Nested Json to Flat Json
// Check the final json in firebug console.
var fullData = {"data":[{"Vehicle":"BMW","Date":"30, Jul 2013 09:24 AM","Location":"Hauz Khas, Enclave, New Delhi, Delhi, India","Speed":42,"Children":[{"Vehicle":"BMW","Date":"30, Jul 2013 09:24 AM","Location":"Hauz Khas, Enclave, New Delhi, Delhi, India","Speed":42,"Children":[{"Vehicle":"BMW","Date":"30, Jul 2013 09:24 AM","Location":"Hauz Khas, Enclave, New Delhi, Delhi, India","Speed":42,"Children":[]}]},{"Vehicle":"Honda CBR","Date":"30, Jul 2013 12:00 AM","Location":"Military Road,  West Bengal 734013,  India","Speed":0,"Children":[]}]},{"Vehicle":"Honda CBR","Date":"30, Jul 2013 12:00 AM","Location":"Military Road,  West Bengal 734013,  India","Speed":0,"Children":[]},{"Vehicle":"Supra","Date":"30, Jul 2013 07:53 AM","Location":"Sec-45, St. Angel's School, Gurgaon, Haryana, India","Speed":58,"Children":[]},{"Vehicle":"Land Cruiser","Date":"30, Jul 2013 09:35 AM","Location":"DLF Phase I, Marble Market, Gurgaon, Haryana, India","Speed":83,"Children":[]},{"Vehicle":"Suzuki Swift","Date":"30, Jul 2013 12:02 AM","Location":"Behind Central Bank RO, Ram Krishna Rd by-lane, Siliguri, West Bengal, India","Speed":0,"Children":[]},{"Vehicle":"Honda Civic","Date":"30, Jul 2013 12:00 AM","Location":"Behind Central Bank RO, Ram Krishna Rd by-lane, Siliguri, West Bengal, India","Speed":0,"Children":[]},{"Vehicle":"Honda Accord","Date":"30, Jul 2013 11:05 AM","Location":"DLF Phase IV, Super Mart 1, Gurgaon, Haryana, India","Speed":71,"Children":[]}]}
var finalData = [];
loopJson(fullData.data);
function loopJson(data) {
    $.each(data, function(i, e) {
        if (e.Children.length>0) {
            var ccd = e.Children;
            delete e.Children;
            finalData.push(e);
            loopJson(ccd);
        } else {
            delete e.Children;
            finalData.push(e);
        }
    });
}
console.log(finalData);
&#13;
&#13;
&#13;

以下是它的小提琴:http://jsfiddle.net/2nwm43yc/