简体   繁体   English

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

[英]Refactor a list of JSON objects to a nested list

I have an array of JSON objects from which I want to create a "single JavaScript object." 我有一个JSON对象数组,我想从中创建“单个JavaScript对象”。 I'd appreciate ideas in Python or JavaScript. 我非常感谢Python或JavaScript中的想法。 In fact, I am not even sure what the proper terminology is to describe (or Google) this kind of question. 实际上,我什至不知道用哪种恰当的术语来描述(或Google)这种问题。 Thanks! 谢谢!

The original list looks like this: 原始列表如下所示:

[
{
    "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"

},

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

And I want it to look like this: 我希望它看起来像这样:

{
    "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
                }
            ]
        }
        .............
    ]
}

I am attempting to use a Python loop like this kind of idea (apologies for any typos, will fix tonight): 我正在尝试使用类似这种想法的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

Using guess work an attempt would be. 使用猜测工作将是一个尝试。

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)

Gives: 给出:

{'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'}

Javascript solution: 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)

The result newData is: 结果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"
                }
            ]
        }
    ]
}

Javascript Solution Javascript解决方案

Here's the fiddle: JSFIDDLE 这是小提琴: JSFIDDLE

Here's the code: 这是代码:

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

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

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