I have a huge JSON file: tribunals.json, that looks like this:
[
{
"city":"05045",
"tribunals":[
{"name":"tribunal 1","value":"path_1"}
]
},
{
"city":"81001",
"tribunals":[
{"name":"tribunal 1","value":"path_1"},
{"name":"tribunal 2","value":"path_2"},
{"name":"tribunal 3","value":"path_3"},
{"name":"tribunal 4","value":"path_4"},
{"name":"tribunal 5","value":"path_5"},
{"name":"tribunal 6","value":"path_6"}
]
}
]
I want to transform it into this:
{
"05045":
{
"tribunal 1": "path_1"
},
"81001":
{
"tribunal 1": "path_1",
"tribunal 2": "path_2",
"tribunal 3": "path_3",
"tribunal 4": "path_4",
"tribunal 5": "path_5",
"tribunal 6": "path_6"
}
}
I've tried different types of iteration over the JSON to obtain de expected output, but none of them worked. For now, I'm doing this:
import json
tribunals = open('tribunals.json',encoding='utf-8')
tribunals = json.load(tribunals)
for tribunal in tribunals:
print(tribunal['city'])
for tribunals_list in tribunal['tribunals']:
print(tribunals_list)
This gives me the next output
05045
{"name":"tribunal 1", "value":"path_1"}
81001
{"name":"tribunal 1","value": "path_1"}
{"name":"tribunal 2","value": "path_2"}
{"name":"tribunal 3","value": "path_3"}
{"name":"tribunal 4","value": "path_4"}
{"name":"tribunal 5","value": "path_5"}
{"name":"tribunal 6","value": "path_6"}
and based on this I'm finishing the work using a text editor, but obviously, the best option is doing this entirely with a script. Any suggestion?
Thanks