简体   繁体   中英

How do I parse JSON with multiple keys the same?

I have json that resembles this:

{"posts":[{"no":3919193, "p": "kekekekek"}, 
          {"no":3929342, "p": "trololol"}]}

I want to extract anything that has the key "no", how would I do this?

I know I can use json.load to parse, but I am unsure how to access each value. Thanks in advance!

You could use a list comprehension to loop through the dicts in obj['posts'] :

obj = json.load(...)
[dct for dct in obj['posts'] if 'no' in dct]

For example,

>>> import json

>>> obj = json.loads('''{"posts":[{"no":3919193, "p": "kekekekek"}, 
          {"no":3929342, "p": "trololol"}]}''')

>>> [dct for dct in obj['posts'] if 'no' in dct]
[{u'no': 3919193, u'p': u'kekekekek'}, {u'no': 3929342, u'p': u'trololol'}]

Once you use json.load you will have a dictionary whose only key points to a list of dictionaries:

data = json.loads("""{"posts":[{"no":3919193, "p": "kekekekek"}, 
      {"no":3929342, "p": "trololol"}]}""")
nos = [i for i in data['posts'] if 'no' in i]

Of course every list element in your example satisfies your requirement that the object have the key "no".

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