将JSON对象列表重构为嵌套列表

时间:2013-02-11 16:38:29

标签: javascript python json

我有一个JSON对象数组,我想从中创建一个"单个JavaScript对象。"我很欣赏Python或JavaScript中的想法。事实上,我甚至不确定描述(或谷歌)这类问题的正确术语是什么。谢谢!

原始列表如下所示:

[
{
    "State_Code": "01",
    "County_Code": "000",
    "State_Abbrv": "AL",
    "County_Name": "ALABAMA",
    "DATA": "12345"

},
{
    "State_Code": "01",
    "County_Code": "001",
    "State_Abbrv": "AL",
    "County_Name": "AUTAUGA COUNTY",
    "DATA": "123"

},
{
    "State_Code": "01",
    "County_Code": "003",
    "State_Abbrv": "AL",
    "County_Name": "BALDWIN COUNTY",
    "DATA": "321"

},
{
    "State_Code": "02",
    "County_Code": "000",
    "State_Abbrv": "AK",
    "County_Name": "ALASKA",
    "DATA": "98765"

},
{
    "State_Code": "02",
    "County_Code": "013",
    "State_Abbrv": "AK",
    "County_Name": "ALEUTIANS EAST BOROU",
    "DATA": "456"

},

..............  ]

我希望它看起来像这样:

{
    "name": "USA",
    "children": [
        {
            "name": "ALABAMA",
            "children": [
                {
                    "name": "AUTAUGA COUNTY",
                    "DATA": 123
                },
                {
                    "name": "BALDWIN COUNTY",
                    "DATA": 321
                }
            ]
        },
        {
            "name": "ALASKA",
            "children": [
                {
                    "name": "ALEUTIANS EAST BOROU",
                    "DATA": 456
                }
            ]
        }
        .............
    ]
}

我试图像这样的想法使用Python循环(对于任何拼写错误道歉,今晚会修复):

runningListCounty = []
tempD = defaultdict(dict)
tempDCounty = defaultdict(dict)
i = 0
for l in listOfJson:
  if l['County_Code'] == '000'
      tempD['name'] = l['County_Name']
      if i > 0: #only do this after the first loop
         tempD['children'] = runningListCounty 
         runningList.append(tempD)       
         runningListCounty = []
         tempD = defaultdict(dict)
  else:
      tempDCounty = defaultdict(dict)
      tempDCounty['name'] = l['County_Name']
      tempDCounty['DATA'] = l['DATA']
      runningListCounty.append(tempDCounty)
  i = i + 1

3 个答案:

答案 0 :(得分:0)

尝试使用猜测工作。

data = [
{
    "State_Code": "01",
    "County_Code": "000",
    "State_Abbrv": "AL",
    "County_Name": "ALABAMA",
    "DATA": "12345"

},
{
    "State_Code": "01",
    "County_Code": "001",
    "State_Abbrv": "AL",
    "County_Name": "AUTAUGA COUNTY",
    "DATA": "123"

},
{
    "State_Code": "01",
    "County_Code": "003",
    "State_Abbrv": "AL",
    "County_Name": "BALDWIN COUNTY",
    "DATA": "321"

},
{
    "State_Code": "02",
    "County_Code": "000",
    "State_Abbrv": "AK",
    "County_Name": "ALASKA",
    "DATA": "98765"

},
{
    "State_Code": "02",
    "County_Code": "013",
    "State_Abbrv": "AK",
    "County_Name": "ALEUTIANS EAST BOROU",
    "DATA": "456"

}
]


roots = [ d for d in data if d['County_Code'] == '000']

def crawl(data, roots):
    for root in roots:
        yield {
            'name' : root['County_Name'],
            'children' : [{ 'name' : d['County_Name'], 'DATA' : d['DATA'] }
                for d in data if d['County_Code'] != '000' and d['State_Code'] == root['State_Code']]
        }


final = { 'name' : 'USA', 'children' : [ x for x in crawl(data, roots)]}

import pprint

pprint.pprint(final)

给出:

{'children': [{'children': [{'DATA': '123', 'name': 'AUTAUGA COUNTY'},
                            {'DATA': '321', 'name': 'BALDWIN COUNTY'}],
               'name': 'ALABAMA'},
              {'children': [{'DATA': '456', 'name': 'ALEUTIANS EAST BOROU'}],
               'name': 'ALASKA'}],
 'name': 'USA'}

答案 1 :(得分:0)

Javascript解决方案:

<强> Demo

var data = [
{
    "State_Code": "01",
    "County_Code": "000",
    "State_Abbrv": "AL",
    "County_Name": "ALABAMA",
    "DATA": "12345"

},
{
    "State_Code": "01",
    "County_Code": "001",
    "State_Abbrv": "AL",
    "County_Name": "AUTAUGA COUNTY",
    "DATA": "123"

},
{
    "State_Code": "01",
    "County_Code": "003",
    "State_Abbrv": "AL",
    "County_Name": "BALDWIN COUNTY",
    "DATA": "321"

},
{
    "State_Code": "02",
    "County_Code": "000",
    "State_Abbrv": "AK",
    "County_Name": "ALASKA",
    "DATA": "98765"

},
{
    "State_Code": "02",
    "County_Code": "013",
    "State_Abbrv": "AK",
    "County_Name": "ALEUTIANS EAST BOROU",
    "DATA": "456"

}
];

var newData = { name : 'USA', children : [] };

for(var i=0; i<data.length; i++) {
    if(data[i].County_Code == "000") {
        newData.children.push({ name : data[i].County_Name, state_code : data[i].State_Code, children : [] });
    }
}

for(var i=0; i<data.length; i++) {
    if(data[i].County_Code != "000") {
        for(var x=0; x<newData.children.length; x++) {
            if(data[i].State_Code == newData.children[x].state_code) {
                newData.children[x].children.push({ name : data[i].County_Name, data : data[i].DATA });
            }
        }
    }
}

console.log(newData); // or convert to JSON with  JSON.stringify(newData)

结果newData是:

{
    "name": "USA",
    "children": [
        {
            "name": "ALABAMA",
            "state_code": "01",
            "children": [
                {
                    "name": "AUTAUGA COUNTY",
                    "data": "123"
                },
                {
                    "name": "BALDWIN COUNTY",
                    "data": "321"
                }
            ]
        },
        {
            "name": "ALASKA",
            "state_code": "02",
            "children": [
                {
                    "name": "ALEUTIANS EAST BOROU",
                    "data": "456"
                }
            ]
        }
    ]
}

答案 2 :(得分:-1)

Javascript解决方案

这是小提琴: 的 JSFIDDLE

以下是代码:

var statesObj = JsonSource,
    finalObj = {
        USA : {
            name: "USA",
            children: []
        }
    };
for (var st = 0; st < statesObj.length; ++st) {
    // First the states
    if( statesObj[st].County_Code === "000") {
        var newState = {
            name: statesObj[st].County_Name,
            abbrv: statesObj[st].State_Abbrv,
            children: []
        };
        finalObj.USA.children.push(newState);
    }
}

for (var st = 0; st < statesObj.length; ++st) {
    // Now the rest
    if( statesObj[st].County_Code !== "000") {
        var newChild = {
            name: statesObj[st].County_Name,
            data: statesObj[st].DATA
        };
        for (var sub in finalObj.USA.children) {
            if (finalObj.USA.children.hasOwnProperty(sub) &&
                finalObj.USA.children[sub].abbrv === statesObj[st].State_Abbrv) {
                finalObj.USA.children[sub].children.push(newChild);
                break;
            }
        }
    }
}

var finalJson = JSON.stringify(finalObj);
console.log(finalJson);