索引JSON搜索python

时间:2013-10-10 19:40:57

标签: python json search

我从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的对象的“abstract”部分。部分“id”是唯一的,因此我可以使用id来索引我的搜索。

谢谢!

3 个答案:

答案 0 :(得分:3)

这是一种方法。您可以通过生成器表达式创建生成器,调用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)。

答案 1 :(得分: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"]

答案 2 :(得分:0)

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

在上面的代码中,数据是列表,每个都是一个dict,你可以轻松访问dict对象。