「単一の JavaScript オブジェクト」を作成したい JSON オブジェクトの配列があります。Python または JavaScript のアイデアをいただければ幸いです。実際、この種の質問を説明する (または Google で検索する) のに適切な用語が何であるかさえ、私にはわかりません。ありがとう!
元のリストは次のようになります。
[
{
"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