简体   繁体   English

使用Python解析嵌套的JSON并返回人类可读的信息

[英]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. 我需要使用python解析嵌套的JSON文件,并将人类可读的信息返回给用户。

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). 我尝试将map()函数alomg与提供解释的字典一起使用,但是它似乎不适用于嵌套JSON(或者我做错了)。 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: 问题还在于,级别2的键可能会重复显示,如下所示,“可消费”和“硬币”内部都具有“ 1”和“ 2”:

My JSONs look like this: 我的JSON如下所示:

{
"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. 我从脚本中期望的是,当我复制JSON时,我将收到人类可读的数据,因此“消耗品1:5”变成“法力药水:5个”,“消耗品2:10”变成“ HP药水”。 :“ 10个”,“硬币1:2000”变成“美元:2000”,“硬币2:5000”变成“欧元:5000”,依此类推。 There are also things without nesting there so they should parse just like regular JSONs. 还有一些东西没有嵌套在那里,因此它们应该像常规JSON一样进行解析。

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 魔力药水:5个
HP potion: 10 pcs 惠普药水:10个
dollar: 2000 美元:2000
euro 5000 5000欧元

A nicer way would be to create a mapping dictionary between json and human readable strings. 更好的方法是在json和人类可读的字符串之间创建一个映射字典。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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