首页 > 解决方案 > 访问 json 响应中的独立值

问题描述

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

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

编辑:

每次我运行此代码时,它都会运行但没有错误。我认为它直接转向“通过”。如果我只使用一切正常

    for i in test_data:
        print(i)

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

标签: jsonpython-3.xpython-requestsresponse

解决方案


你很亲密。我认为您正在寻找两个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

推荐阅读