2012-10-17 43 views
18

使用Python,我怎樣才能將字段id提取到變量? Basicaly,我改造這個:從JSON輸出中選擇字段

{ 
    "accountWide": true, 
    "criteria": [ 
     { 
      "description": "some description", 
      "id": 7553, 
      "max": 1, 
      "orderIndex": 0 
     } 
    ] 
} 

喜歡的東西

print "Description is: " + description 
print "ID is: " + id 
print "Max value is : " + max 
+1

你可以看看http://docs.python.org/library/json.html一切都可以在那裏找到。 – cb0

回答

25

假設你存儲在字典中的變量名爲值。要獲得id在一個變量,這樣做:

idValue = values['criteria'][0]['id'] 

如果JSON是在一個文件中,執行以下操作加載它:

import json 
jsonFile = open('your_filename.json', 'r') 
values = json.load(jsonFile) 
jsonFile.close() 

如果JSON是從一個URL,請執行下列操作加載它:

import urllib, json 
f = urllib.urlopen("http://domain/path/jsonPage") 
values = json.load(f) 
f.close() 

打印所有的標準,你可以:

for criteria in values['criteria']: 
    for key, value in criteria.iteritems(): 
     print key, 'is:', value 
    print '' 
+0

嗨,實際上它是一個http輸出。我會嘗試將您的示例轉換爲解析網站的輸出。 –

+1

@Thales請參閱http://docs.python.org/library/urllib.html#examples的示例部分取出'urllib.urlopen'返回的值並將其傳遞給'json.load'來代替'jsonFile '我上面的例子。 – bohney

4

假設您正在處理輸入中的JSON字符串,可以使用json包進行解析,請參閱documentation

在具體的例子中,你發佈你需要

x = json.loads("""{ 
"accountWide": true, 
"criteria": [ 
    { 
     "description": "some description", 
     "id": 7553, 
     "max": 1, 
     "orderIndex": 0 
    } 
    ] 
}""") 
description = x['criteria'][0]['description'] 
id = x['criteria'][0]['id'] 
max = x['criteria'][0]['max'] 
+0

如何訪問所有更高級別實體的所有描述(或ID)? – InquilineKea