【AI】使用 Python 解析和输出成功的问答对 JSON 数据
warning:
这篇文章距离上次修改已过192天,其中的内容可能已经有所变动。
import json
# 假设这是从文件中读取的JSON字符串
json_data = """
[
{
"question": "你好,世界!",
"answer": "你好!我是智能助手。"
},
{
"question": "你好,人类!",
"answer": "你好!我很高兴认识你。"
}
]
"""
# 将JSON字符串解析成Python对象
data = json.loads(json_data)
# 输出解析后的数据
for item in data:
print(f"问题: {item['question']}")
print(f"答案: {item['answer']}\n")
# 如果需要将数据写入文件,可以使用json.dump()或json.dumps()
# json.dump(data, open('output.json', 'w'), indent=4) # 将数据写入output.json文件,格式化输出
这段代码首先导入了json
模块,然后定义了一个JSON格式的字符串json_data
。使用json.loads()
函数将字符串解析成Python的字典列表。然后遍历字典列表,打印出每个问题和答案。最后,可以选择将解析后的数据写入到一个新的JSON文件中。
评论已关闭