【问题标题】:Selecting fields from JSON output从 JSON 输出中选择字段
【发布时间】:2012-10-17 12:49:38
【问题描述】:

使用 Python,我如何将字段 id 提取到变量中?基本上,我要改变这个:

{
    "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

【问题讨论】:

标签: python


【解决方案1】:

假设您将该字典存储在一个名为 values 的变量中。要将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 ''

【讨论】:

  • 您好,其实是http输出。我将尝试将您的示例转换为解析网站的输出。
  • @Thales 请参阅以下示例部分:docs.python.org/library/urllib.html#examples 获取urllib.urlopen 返回的值并将其传递给json.load,代替我上面的示例jsonFile
【解决方案2】:

假设您正在处理输入中的 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']

【讨论】:

  • 如何访问所有更高级别实体的所有描述(或 ID)?
猜你喜欢
  • 1970-01-01
  • 2021-12-11
  • 2017-12-27
  • 2017-12-31
  • 2019-04-12
  • 2019-01-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多