0

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

2
  • why printing instead of turning that into the dictionary you're asking for? Commented Jan 7, 2021 at 16:07
  • @Sayse, That's what I've tried but I don't know how to do it, This is the reason for posted it here. Maybe it requires a little changed in the code but I've tried hours without achieving it! Commented Jan 7, 2021 at 16:11

1 Answer 1

2
import json

tribunals = open('tribunals.json',encoding='utf-8')
tribunals = json.load(tribunals)

result = {}

for tribunal in tribunals:
    result[tribunal['city']] = {}
    for item in tribunal['tribunals']:
        result[tribunal['city']][item['name']] = item['value']

print(result)
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! That's exactly what I'm wanted!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.