你可以使用json模块解析该数据:
import pprint
import json
pp = pprint.PrettyPrinter(indent=4)
question_data = '''{
"response_code": 0,
"results": [
{
"type": "multiple",
"difficulty": "medium",
"category": "Entertainment: Film",
"question": "Sign of death.",
"correct_answer": "Red Shirt",
"incorrect_answers": [
"Minions",
"Expendables",
"Cannon Fodder"
]
}
]
}'''
print("为了更好地查看数据结构:")
pp.pprint(question_data)
y = json.loads(question_data)
# print(y)
# 遍历字典的所有键值对
for k, v in y.items():
print(f"键: {k} 值: {v}\n")
##############################################
print("\n值内容:") # 使用列表推导式循环
##############################################
# 访问response_code
print("response_code:", [v for k, v in y.items() if k == "response_code"])
# 访问例如category(以及类似地,访问列表中其他项的值)
print("category:", [v for k, v in y['results'][0].items() if k == "category"])
# 访问incorrect_answers列表的第一个元素
print("incorrect_answers:", y['results'][0]['incorrect_answers'][0])
输出结果:
为了更好地查看数据结构:
{
"response_code": 0,
"results": [
{
"type": "multiple",
"difficulty": "medium",
"category": "Entertainment: Film",
"question": "Sign of death.",
"correct_answer": "Red Shirt",
"incorrect_answers": [
"Minions",
"Expendables",
"Cannon Fodder"
]
}
]
}
键值对内容:
键: response_code 值: 0
键: results 值: [{'type': 'multiple', 'difficulty': 'medium', 'category': 'Entertainment: Film', 'question': 'Sign of death.', 'correct_answer': 'Red Shirt', 'incorrect_answers': ['Minions', 'Expendables', 'Cannon Fodder']}]
值内容:
response_code: [0]
category: ['Entertainment: Film']
incorrect_answers: Minions