访问 json 响应中的独立值

Access standalone values in json responses

作为对请求的响应,我有以下输出:

{
    [
        "1545904980",             //val1
        "0.058",                  //val2
        "0.049",                  //val3
        "0.058",                  //val4
        "0.049",                  //val5
        "0.018",                  //val6
        "0.000945"                //val7
    ],
    [
        "1545904920",
        "0.058",
        "0.072",
        "0.072",
        "0.058",
        "0.103",
        "0.006986"
    ]
}

假设我想访问 val3,因此“0.049”,这就是我使用的:

    test = requests.get("url")

    # to load response into json we must convert response to string
    test_list = str(test.json())

    #before loading response into json we must convert '' string to "" type string.
    s_test = test_list.replace("\'", "\"")
    test_data = json.loads(s_test)
    
    for i in test_data:
        for j in i:
            print(i[2])
    pass

编辑:

每次我 运行 这段代码都只是 运行s 但没有错误。我认为它直接移动到“通过”。如果我只使用

一切正常
    for i in test_data:
        print(i)

但这会打印出整个 JSON 对象,这不是目标。关于如何访问这些特定值的任何帮助?

你很接近。我认为您正在寻找两个 for 循环尝试的混合体。

import json

s_test = '''
[
    ["1545904980", "0.058", "0.049", "0.058", "0.049", "0.018", "0.000945"],
    ["1545904920", "0.058", "0.072", "0.072", "0.058", "0.103", "0.006986"]
]
'''
test_data = json.loads(s_test)

for row in test_data:
    print(row[2])

应该给你:

0.049
0.072

你可以直接这样做:

import requests

response = requests.get("url")

data = response.json()

for row in data:
    print(row[2])

这是对我有用的解决方案:

test = requests.get("url")
test_data = test['data']


for i in range(len(test_data)):
    for j in test_data[i]:
        if test_data[i]['dict_key'] == 'any_value':
            # do something here
        else:
            i = i + 1

这将遍历字典列表。