Доступ к вложенным элементам в python JSON - PullRequest
0 голосов
/ 11 января 2020

Я загружаю JSON файл со следующей структурой:

{"questions": 
     [{"question_id": 0, "image_filename": "CLEVR_val_009641.png", "question": "Are there any tiny green things made of the same material as the small brown sphere?"}, 
     {"question_id": 1, "image_filename": "CLEVR_val_010849.png", "question": "Are there any purple metal things of the same size as the green shiny object?"}, 
     {"question_id": 2, "image_filename": "CLEVR_val_004213.png", "question": "Is there a big thing of the same color as the big metal ball?"}, 
     {"question_id": 3, "image_filename": "CLEVR_val_012597.png", "question": "There is a big metallic thing to the right of the blue rubber object; are there any small cyan rubber blocks that are to the right of it?"}, 
     {"question_id": 4, "image_filename": "CLEVR_val_006304.png", "question": "Is there any other thing that has the same material as the small brown object?"}
     ]
}

Я использую json.loads() для загрузки файла.

Пока, используя:

train_data_jsonload = json.load(f)
train_data = train_data_jsonload.get("questions")

Мне удалось загрузить весь «набор данных».

Я хотел бы загрузить только ключ question в моем файле json (поэтому все вопросы, без question_id и image_filename)

Я пытался использовать train_data.get("question"), но я получаю ошибку list object has no attribute 'get'

Я также пытался использовать то, что было предложено здесь: Вложенный словарь безуспешно

Итак, вернемся к моему вопросу, как выбрать только поля question?

Ответы [ 3 ]

1 голос
/ 11 января 2020

try_this:

train_data_jsonload = json.load(f)
for questions_info in train_data_jsonload["questions"]:
   question  = question_info["question"]
   #Do required stuff here if needed.
0 голосов
/ 11 января 2020

В конце концов я нашел решение:

for element in train_data:
    print(element.get("question"))

Напечатает каждый вопрос.

0 голосов
/ 11 января 2020

Если вы хотите получить список вопросов в качестве вывода, просто используйте понимание списка:

text_questions = [item["question"] for item in train_data_jsonload.get("questions")]

...