簡體   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