下一个JSON来自URL:
[{
"id": 1,
"version": 23,
"external_id": "2312",
"url": "https://example.com/432",
"type": "typeA",
"date": "2",
"notes": "notes",
"title": "title",
"abstract": "dsadasdas",
"details": "something",
"accuracy": 0,
"reliability": 0,
"severity": 12,
"thing": "32132",
"other": [
"aaaaaaaaaaaaaaaaaa",
"bbbbbbbbbbbbbb",
"cccccccccccccccc",
"dddddddddddddd",
"eeeeeeeeee"
],
"nana": 8
},
{
"id": 2,
"version": 23,
"external_id": "2312",
"url": "https://example.com/432",
"type": "typeA",
"date": "2",
"notes": "notes",
"title": "title",
"abstract": "dsadasdas",
"details": "something",
"accuracy": 0,
"reliability": 0,
"severity": 12,
"thing": "32132",
"other": [
"aaaaaaaaaaaaaaaaaa",
"bbbbbbbbbbbbbb",
"cccccccccccccccc",
"dddddddddddddd",
"eeeeeeeeee"
],
"nana": 8
}]
我的代码:
import json
import urllib2
data = json.load(urllib2.urlopen('http://someurl/path/to/json'))
print data
例如,我想知道如何访问“id”等于2的对象的“abstract”部分。部分“id”是唯一的,所以我可以使用id来索引我的搜索。
谢谢!
您可以使用列表理解来筛选:
然后可以打印“抽象”值,如下所示:
这里有一种方法。您可以通过生成器表达式创建生成器,调用
next
迭代该生成器一次,然后返回所需的对象。另见Python: get a dict from a list based on something inside the dict
编辑:如果希望访问具有给定键值(例如,
id == 2
)的列表的所有元素,可以执行以下两种操作之一。您可以通过理解创建一个列表(如另一个答案所示),也可以更改我的解决方案:在循环中,
item
将遍历列表中满足给定条件的那些项(这里,id == 2
)。在上面的代码中,数据是list,每个数据都是dict,您可以很容易地访问dict对象。
相关问题 更多 >
编程相关推荐