提取JSON元素

时间:2018-07-01 02:37:59

标签: python json

我从下面显示的网站收到JSON响应。我想打印'value'的{​​{1}}和'datetime'键。我无法在JSON响应中访问这两个元素。

data

我的代码至今

  data= {"parameter_name":"Inst",
    "parameter_code":"WL1","data":[
    {"value":3.1289999485,"datetime":"2018-07-01T00:00:00+00:00"},
    {"datetime":"2018-07-01T00:30:00+00:00","value":3.1859998703},
    {"value":3.33099985123,"datetime":"2018-07-01T00:45:00+00:00"},
    {"datetime":"2018-07-01T01:15:00+00:00","value":3.22300004959},
    {"datetime":"2018-07-01T01:45:00+00:00","value":3.32299995422}]}

我遇到错误

for element in len(data['data']):
            date = element['datetime']
            value = element['value']

            print value, date

3 个答案:

答案 0 :(得分:2)

您可以尝试这样:

for element in data['data']:
    date = element['datetime']
    value = element['value']

print(date)
print(value)

输出:

3.1289999485
2018-07-01T00:00:00+00:00
3.1859998703
2018-07-01T00:30:00+00:00
3.33099985123
2018-07-01T00:45:00+00:00
3.22300004959
2018-07-01T01:15:00+00:00
3.32299995422
2018-07-01T01:45:00+00:00

说明:

如果要遍历list中的元素,则:

 for element in data['data']

如果要使用其索引遍历列表:

 for index in range(len(data['data'])):

答案 1 :(得分:2)

您显示为JSON data的内容 可能不是data的实际值。如果尝试像Python dict一样访问数据,它将引发TypeError: string indices must be integers, not str。您的JSON data可能看起来像这样(注意引号):

# This is JSON, essentialy a string in the format of a Python dict.
data = """{
    "parameter_name": "Inst",
    "parameter_code": "WL1",
    "data":[
        {
            "value":3.1289999485,
            "datetime":"2018-07-01T00:00:00+00:00"
        },
        {
            "datetime":"2018-07-01T00:30:00+00:00",
            "value":3.1859998703
        },
        {
            "value":3.33099985123,
            "datetime":"2018-07-01T00:45:00+00:00"
        },
        {
            "datetime":"2018-07-01T01:15:00+00:00",
            "value":3.22300004959
        },
        {
            "datetime":"2018-07-01T01:45:00+00:00",
            "value":3.32299995422
        }
    ]
}"""

使用Python标准库dict软件包将其转换为Python json

import json

# This converts the JSON string into a Python dict
data = json.loads(data)

您可以访问data及其“数据”键,然后对其进行迭代(就像您之前所做的那样):

for element in data['data']:
    print(element['value'], element['datetime'])

答案 2 :(得分:1)

如果您有文本格式的网络回复,则还必须先对其进行解码。校验 https://docs.python.org/2/library/json.html(对于python 2)或https://docs.python.org/3.7/library/json.html(对于python 3),以查看有关json库的文档。 您必须:

import json
decodedData = json.loads(data)

,然后按照您的操作循环遍历decodedData。