2012-10-17 47 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