读取一个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"
  }
]
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值