简体   繁体   中英

Parse a nested JSON with Python and return human-readable info

I need to parse a nested JSON file with python and return the human-readable information back to the user.

I have tried applying a map() function alomg with dictionary that provides interpretation, but it seems to be not working with nested JSONs (or I am doing it wrong). The problem is also that the keys at level 2 may repeat as shown below, both 'consumable' and 'coin' have '1' and '2' inside them:

My JSONs look like this:

{
"consumable": {
"1": 5,
"2": 10
},
"coin": {
"1": 2000,
"2": 5000
},
"gold": 10000
}

What I expect from my script is that when I copy the JSON, I will receive a human-readable data, so 'consumable 1: 5' becomes 'mana potion: 5 pcs', ''consumable 2: 10' becomes 'HP potion: 10 pcs', and 'coin 1: 2000' becomes 'dollar: 2000', 'coin 2: 5000' becomes 'euro: 5000' and so on. There are also things without nesting there so they should parse just like regular JSONs.

I'm not even a programmer, and have no idea how this might be done.

Not very pretty but does what you're expecting:

import json
json_string = '{ "consumable": { "1": 5, "2": 10 }, "coin": { "1": 2000, "2": 5000 }, "gold": 10000}'

content = json.loads(json_string)

for elem in content:
    if elem == 'consumable':
        for index in content[elem]:
            if index == '1':
                print(f'mana potion: {content[elem][index]} pcs')
            elif index == '2':
                print(f'HP potion: {content[elem][index]} pcs')
    elif elem == 'coin':
        for index in content[elem]:
            if index == '1':
                print(f'dollar: {content[elem][index]}')
            elif index == '2':
                print(f'euro: {content[elem][index]}')

This prints:

mana potion: 5 pcs
HP potion: 10 pcs
dollar: 2000
euro 5000

A nicer way would be to create a mapping dictionary between json and human readable strings.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM