无法打印此Json,Python

时间:2019-04-30 12:12:00

标签: python json

因此,我将数据另存为结构如下:

的json文件
{
"Users": [
{
  "BOB": [
    {
      "Computer Name": "Bob Pc",
      "Manufacturer": "Dell Inc.",
      "Make": "Precision Tower 3620",
      "Os": "Microsoft Windows 10 Pro",
      "Cpu": "Intel(R) Core(TM) i5-6600 CPU @ 3.30GHz",
      "Memory": "8589934592",
      "Slots": "4",
      "Used Slots": "1"
    }
  ] 
},
{
  "Sally": [
    {
      "Computer Name": "Sally PC",
      "Manufacturer": "Dell Inc.",
      "Make": "Precision Tower 3620",
      "Os": "Microsoft Windows 10 Pro",
      "Cpu": "Intel(R) Core(TM) i5-6600 CPU @ 3.30GHz",
      "Memory": "8589934592",
      "Slots": "4",
      "Used Slots": "1"
    }
      ]
}
  ]
}

如果我想打印我可以做的全部事情

with open(filename) as f:
    data = json.load(f)

    print(data)

那样就可以了,但是现在,如果我想在“鲍勃”中打印所有信息怎么办?

我尝试过:

print(data["Users"]["Bob"])

哪一个错误列表索引必须是整数或切片,而不是str

2 个答案:

答案 0 :(得分:0)

name = 'BOB'
for item in data["Users"]:
    if name in item.keys():
        print(item)

输出:

{'BOB': [{'Computer Name': 'Bob Pc', 'Manufacturer': 'Dell Inc.', 'Make': 'Precision Tower 3620', 'Os': 'Microsoft Windows 10 Pro', 'Cpu': 'Intel(R) Core(TM) i5-6600 CPU @ 3.30GHz', 'Memory': '8589934592', 'Slots': '4', 'Used Slots': '1'}]}

答案 1 :(得分:0)

ncica的答案很好。另一种选择是将data转换为您期望的格式。

users = {name_: dict_ for user in data['users'] for name_, dict_ in user.items()}
print(users["Bob"])