I have an array of JSON objects from which I want to create a "single JavaScript object." I'd appreciate ideas in Python or JavaScript. In fact, I am not even sure what the proper terminology is to describe (or Google) this kind of question. 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):
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