0

So I am saving data as a json file that is Structured like so:

{
"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"
    }
      ]
}
  ]
}

If I want to print the whole thing I can do

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

    print(data)

That will do it but now what if I want to print all the info in "Bob"?

I Tried:

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

Which gives an error list indices must be integers or slices, not str

Kiffness
  • 15
  • 5

2 Answers2

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

output:

{'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'}]}
ncica
  • 7,015
  • 1
  • 15
  • 37
0

The answer of ncica works well. The other option is to convert data to the format you expect.

users = {name_: dict_ for user in data['users'] for name_, dict_ in user.items()}
print(users["Bob"])
Roelant
  • 4,508
  • 1
  • 32
  • 62