Доступ к объектам словаря в Python и JSON - PullRequest
0 голосов
/ 09 ноября 2019

Как идентифицировать каждый объект в диктанте. Я ожидаю, ожидая первого и последнего из записей.

#!/usr/bin/python
import json


with open("test_data.json", "r") as read_file:
    data = json.load(read_file)

for each in data:
        print(each[0]["traits"][0]["disease"])
        print(each[1]["traits"][1]["disease"])

print(data)

JSON

{
    "userId": 1,
    "id": 1,
    "name": "del aut",
    "completed": false,
    "traits": [
        {"bodypart": "head", "disease": "headache"},
        {"bodypart": "chest", "disease": "asthma"}
        ],


    "userId": 2,
    "id": 2,
    "name": "wokey",
    "completed": true,
    "traits": [
        {"bodypart": "cns", "disease": "nuropathy"},
        {"bodypart": "bone", "disease": "artheritis"}
        ]
}

ошибка

Traceback (most recent call last):
  File "./seer.core.py", line 20, in <module>
    print(each[0]["traits"][1]["disease"])
TypeError: string indices must be integers

печать Json

print(data) 
{'userId': 2, 'id': 2, 'name': 'wokey', 'completed': True, 'traits': [{'bodypart': 'cns', 'disease': 'nuropathy'}, {'bodypart': 'bone', 'disease': 'artheritis'}]}

1 Ответ

1 голос
/ 09 ноября 2019

import json


with open("json.json", "r") as read_file:
    data = json.load(read_file)


for k, v in data.items():
    if(k=='traits'):
        for i in v:
            print(i['bodypart']),print(i['disease'])

enter image description here

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...