如何解析具有多个相同键的JSON? [英] How do I parse JSON with multiple keys the same?

查看:191
本文介绍了如何解析具有多个相同键的JSON?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个与此类似的json:

I have json that resembles this:

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

我想提取任何带有键"no"的东西,我该怎么做?

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

我知道我可以使用json.load进行解析,但是我不确定如何访问每个值.预先感谢!

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

推荐答案

您可以使用列表推导式遍历obj['posts']中的命令:

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]

例如,

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

这篇关于如何解析具有多个相同键的JSON?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆