从 JSON 输出中选择字段 [英] Selecting fields from JSON output
本文介绍了从 JSON 输出中选择字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
使用 Python,如何将字段 id
提取到变量?基本上,我要转换这个:
Using Python, how can i extract the field id
to a variable? Basicaly, i to transform this:
{
"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
推荐答案
假设您将该字典存储在名为 values 的变量中.要将 id
放入变量,请执行以下操作:
Assume you stored that dictionary in a variable called values. To get id
in to a variable, do:
idValue = values['criteria'][0]['id']
如果该 json 在文件中,请执行以下操作以加载它:
If that json is in a file, do the following to load it:
import json
jsonFile = open('your_filename.json', 'r')
values = json.load(jsonFile)
jsonFile.close()
如果该 json 来自 URL,请执行以下操作以加载它:
If that json is from a URL, do the following to load it:
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 ''
这篇关于从 JSON 输出中选择字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文