在Python中遍历Json

时间:2017-12-27 05:22:53

标签: python json

我有这个json,我想知道是否有人可以帮助我弄清楚得到'1。打开以下json的值。使用python。感谢

{
"Meta Data": {
    "1. Information": "Daily Prices (open, high, low, close) and Volumes",
    "2. Symbol": "AAPL",
    "3. Last Refreshed": "2017-12-26",
    "4. Output Size": "Compact",
    "5. Time Zone": "US/Eastern"
},
"Time Series (Daily)": {
    "2017-12-26": {
        "1. open": "170.8000",
        "2. high": "171.4700",
        "3. low": "169.6790",
        "4. close": "170.5700",
        "5. volume": "33106577"
    },
    "2017-12-22": {
        "1. open": "174.6800",
        "2. high": "175.4240",
        "3. low": "174.5000",
        "4. close": "175.0100",
        "5. volume": "16052615"
    },
    "2017-12-21": {
        "1. open": "174.1700",
        "2. high": "176.0200",
        "3. low": "174.1000",
        "4. close": "175.0100",
        "5. volume": "20356826"
    },

1 个答案:

答案 0 :(得分:0)

使用json模块将JSON转换为python的字典。然后很容易。

data = '''{
    "Meta Data": {
        "1. Information": "Daily Prices (open, high, low, close) and Volumes",
        "2. Symbol": "AAPL",
        "3. Last Refreshed": "2017-12-26",
        "4. Output Size": "Compact",
        "5. Time Zone": "US/Eastern"
    },
    "Time Series (Daily)": {
        "2017-12-26": {
            "1. open": "170.8000",
            "2. high": "171.4700",
            "3. low": "169.6790",
            "4. close": "170.5700",
            "5. volume": "33106577"
        },
        "2017-12-22": {
            "1. open": "174.6800",
            "2. high": "175.4240",
            "3. low": "174.5000",
            "4. close": "175.0100",
            "5. volume": "16052615"
        },
        "2017-12-21": {
            "1. open": "174.1700",
            "2. high": "176.0200",
            "3. low": "174.1000",
            "4. close": "175.0100",
            "5. volume": "20356826"
        }
    }
}'''

import json

data = json.loads(data)

for key, val in data['Time Series (Daily)'].items():
    print(key, val["1. open"])

结果:

2017-12-26 170.8000
2017-12-22 174.6800
2017-12-21 174.1700

如果您遇到结构方面的问题,那么您可以使用print(item)print(type(item))来显示项目及其类型,并print(item.keys())查看是否为字典的密钥。

print(type(data))
print(data.keys())

# <class 'dict'>
# dict_keys(['Meta Data', 'Time Series (Daily)'])

print(type(data['Time Series (Daily)']))
print(data['Time Series (Daily)'].keys())

# <class 'dict'>
# dict_keys(['2017-12-26', '2017-12-22', '2017-12-21'])