繁体   English   中英

索引JSON搜索python

[英]Index JSON searches python

我有一个从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:根据字典中的内容从列表中获取字典

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

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

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

您可以使用列表理解来过滤:

import json

j = """[{"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}]"""

dicto = json.loads(j)

results = [x for x in dicto if "id" in x and x["id"]==2]

然后,您可以打印“抽象”值,如下所示:

for result in results:
    if "abstract" in result:
        print result["abstract"]
import urllib2
import json
data = json.load(urllib2.urlopen('http://someurl/path/to/json'))
your_id = raw_input('enter the id')
for each in data:
    if each['id'] == your_id:
        print each['abstract']

在上面的代码中,数据为list,每个数据都是dict,您可以轻松访问dict对象。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM