如何使用Python访问JSON子数据

时间:2018-08-20 15:08:38

标签: python

我正在使用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"]

两个抛出错误。任何帮助将不胜感激。

4 个答案:

答案 0 :(得分:4)

尝试一下:

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")

答案 1 :(得分:2)

我尝试了这个简单的例子,它可以工作:

array_of_integers = [[1,2,3],[2,4,5]....]
values = []
array_of_integers.each_with_index do |array, index|
  values = if index.zero?
          array
        else
          values & array
        end
end
# `values` will be an array of common values

执行此操作时的错误消息是什么:

import json
j = '{"u":[{"a":1},{"a":2},{"a":3}]}'
d=json.loads(j)
print(d["u"][1]["a"])
# output: 2

答案 2 :(得分:1)

在以上答案中,您只需添加一个列表并获取所有名称。

data = {
    "users": [
        {
            "name": "John Doe",
            "prefix": "[Test Account]",
            "rank": "10"
        },
        {
            "name": "Jane Doe",
            "prefix": "[Test Account]",
            "rank": "10"
        }
    ]
}
username = "John Doe"
names = []
for x in data["users"]:
    names.append(x["name"])


>>names
['John Doe', 'Jane Doe']

答案 3 :(得分:0)

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

for x in data['users']:
  print(x['name'])