How to parse JSON with multiple keys the same way?

I have json that resembles this:

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

I want to extract everything that has a no key, how would I do it?

I know what I can use json.loadfor parsing, but I'm not sure how to access each value. Thanks in advance!

+1
source share
2 answers

You can use list comprehension to scroll dicts to obj['posts']:

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

For instance,

>>> 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'}]
0
source

As soon as 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, each list item in your example satisfies your requirement that the object has a no key.

0
source

All Articles