读取一个json文件中的部分内容写入另一个json文件

读取一个json文件中的部分内容写入另一个json文件

首先是第一个json文件:

[
{
    "id": 1,
    "context": "Xiao Li was admitted to Tsinghua University.",
    "question": "Which of the following conditions should be added to conclude that Xiao Li was admitted to Tsinghua University?",
    "A": "At least one of Xiao Zhang and Xiao Li failed to enter Tsinghua University.",
    "B": "Both Xiao Zhang and Xiao Sun have been admitted to Peking University.",
    "answer": "B"
    },
    {
    "id": 2,
    "context": "If it is an unchangeable fact that you can't have your cake and eat it, then either of the following must also be true ",
    "question": "Is it a fact?",
    "A": "Get a fish but not a bear's paw.",
    "B": "If you get a fish, you don't get a bear's paw.",
    "answer": "B"
    }
]

我只想要其中的context和answer数据:

import os
import random
import json
import string

path = "test.json"
file = open(path, encoding='utf-8')
jsondata = json.load(file)

json_all = []  
for i in range(len(jsondata)):
    json_single = {}     #每一条数据
    json_single["context"] = jsondata[i]["context"]
    json_single["answer"] = jsondata[i]["answer"]
    json_all.append(json_single)


new_path = 'json/result.json'    #写入一个新的json文件
json_str = json.dumps(json_all, indent=2, ensure_ascii=False)
json_file = open(new_path, 'w', encoding='utf-8')
json_file.write(json_str)
json_file.close()


输出结果result.json:

[
  {
    "context": "Xiao Li was admitted to Tsinghua University.",
    "answer": "B"
  },
  {
    "context": "If it is an unchangeable fact that you can't have your cake and eat it, then either of the following must also be true ",
    "answer": "B"
  }
]