我有一个 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