简体   繁体   English

python中的JSON解析(特殊情况)

[英]JSON Parse in python (special case)

My project is receiving a JSON message which look like this: 我的项目正在接收如下所示的JSON消息:

"listinginfo":{
    "438317215072450609":{
        "listingid":"438317215072450609",
        "price":27044,
        "fee":4056,
    },
    "428184115913903011":{
        "listingid":"428184115913903011",
        "price":480,
        "fee":72,
    }
}

In this json file, I want to get "438317215072450609" and "428184115913903011". 在此json文件中,我想获取“ 438317215072450609”和“ 428184115913903011”。 I've tried : 我试过了 :

myjson.get('listinginfo').get(*).get(listingid)
#and
myjson['listinginfo'][0]['listingid']

But of course, it doesn't work ;) Thank you in advance (sorry for this bad english) 但是,当然,这是行不通的;)预先谢谢您(抱歉英语不好)

You have those values twice: once as the key in the outer dict, and once as the listingid value inside the inner dict. 这些值有两次:一次是外部dict中的键,一次是内部dict中的listingid值。 To get the first, you can just do: 要获得第一个,您可以执行以下操作:

myjson['listinginfo'].keys()

and to get the second, you can do: 要获得第二个,您可以执行以下操作:

[d['listingid'] for d in myjson['listinginfo'].values()]

If they're always the same, of course, it doesn't matter which of these you use. 当然,如果它们始终相同,那么使用哪一个都无所谓。

First you need to make your "JSON" string valid JSON by surrounding it with { and } and removing the trailing commas in the inner objects. 首先,您需要使用{}将“ JSON”字符串设为有效JSON,并删除内部对象中的结尾逗号。 I edited the string by hand instead of with code, because this should really be fixed in the code producing that "JSON". 我手动编辑了该字符串,而不是使用代码,因为在生成该“ JSON”的代码中应该确实解决了这一问题。

myjson = '''{"listinginfo":{
                "438317215072450609":{
                    "listingid":"438317215072450609",
                    "price":27044,
                    "fee":4056
                },
                "428184115913903011":{
                    "listingid":"428184115913903011",
                    "price":480,
                    "fee":72
                }
            }}'''

Then turn the string into a python data structure: 然后将字符串转换为python数据结构:

import json
data = json.loads(myjson)

Then extract what you want: 然后提取您想要的内容:

ids = data['listinginfo'].keys()

Or if the ID is not always also the key of the object: 或者,如果ID并不总是对象的键,也可以:

ids = [d['listingid'] for d in data['listinginfo'].values()]

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

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