Python 从 JSON 输出中选择字段
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12934699/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Selecting fields from JSON output
提问by thclpr
Using Python, how can i extract the field idto a variable? Basicaly, i to transform this:
使用 Python,如何将字段提取id到变量?基本上,我要转换这个:
{
"accountWide": true,
"criteria": [
{
"description": "some description",
"id": 7553,
"max": 1,
"orderIndex": 0
}
]
}
to something like
像
print "Description is: " + description
print "ID is: " + id
print "Max value is : " + max
采纳答案by bohney
Assume you stored that dictionary in a variable called values. To get idin to a variable, do:
假设您将该字典存储在名为 values 的变量中。要进入id变量,请执行以下操作:
idValue = values['criteria'][0]['id']
If that json is in a file, do the following to load it:
如果该 json 在文件中,请执行以下操作以加载它:
import json
jsonFile = open('your_filename.json', 'r')
values = json.load(jsonFile)
jsonFile.close()
If that json is from a URL, do the following to load it:
如果该 json 来自 URL,请执行以下操作以加载它:
import urllib, json
f = urllib.urlopen("http://domain/path/jsonPage")
values = json.load(f)
f.close()
To print ALL of the criteria, you could:
要打印所有条件,您可以:
for criteria in values['criteria']:
for key, value in criteria.iteritems():
print key, 'is:', value
print ''
回答by user8472
Assuming you are dealing with a JSON-string in the input, you can parse it using the jsonpackage, see the documentation.
假设您正在处理输入中的 JSON 字符串,您可以使用json包解析它,请参阅文档。
In the specific example you posted you would need
在您发布的特定示例中,您需要
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']

