首页 > 解决方案 > 如何使用 Python 访问 JSON 子数据

问题描述

我正在使用 Python 处理一些 JSON 数据。基本上我有以下 JSON 数据

{
    "users": [
        {
            "name": "John Doe",
            "prefix": "[Test Account]",
            "rank": "10"
        },
        {
            "name": "Jane Doe",
            "prefix": "[Test Account]",
            "rank": "10"
        }
    ]
}

我有一个循环成功地遍历 Python 中的用户。

for x in data["users"]:
    if username == data["users"]["name"]:
        print("true")

我只想获得name价值。在 JS 中你会这样做

data.users[x].name

但是你如何在 Python 中做到这一点。我试过像

data["users"][x]["name"]

data["users"[x]]["name"]

两者都抛出错误。任何帮助是极大的赞赏。

标签: python

解决方案


尝试这个:

data = {
    "users": [
        {
            "name": "John Doe",
            "prefix": "[Test Account]",
            "rank": "10"
        },
        {
            "name": "Jane Doe",
            "prefix": "[Test Account]",
            "rank": "10"
        }
    ]
}
username = "John Doe"

for x in data["users"]:
    if username == x["name"]:
        print("true")

推荐阅读