gpt4 book ai didi

python - 索引 JSON 搜索 python

转载 作者:太空宇宙 更新时间:2023-11-04 09:07:10 24 4
gpt4 key购买 nike

我有下一个从 URL 获得的 JSON:

[{
"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 的对象的“抽象”部分。 “id”部分是唯一的,所以我可以使用 id 来索引我的搜索。

谢谢!

最佳答案

这是一种方法。您可以通过生成器表达式创建一个生成器,调用 next 来迭代该生成器一次,然后取回所需的对象。

item = next((item for item in data if item['id'] == 2), None)
if item:
print item['abstract']

另见 Python: get a dict from a list based on something inside the dict

编辑:如果您想访问列表中具有给定键值的所有元素(例如,id == 2) 你可以做两件事之一。您可以通过理解创建列表(如其他答案所示),也可以更改我的解决方案:

my_gen = (item for item in data if item['id'] == 2)
for item in my_gen:
print item

在循环中,item 将遍历列表中满足给定条件(此处为 id == 2)的项目。

关于python - 索引 JSON 搜索 python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19304776/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com