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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 12:12:47  来源:igfitidea点击:

Selecting fields from JSON output

python

提问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']