python jsonl格式文件转为json格式文件

文章提供了将jsonl文件转换为两种不同格式的json文件的Python代码。一种是将jsonl数据合并成一个大对象,另一种是转换为一个包含多个对象的数组。转换过程中考虑了处理多答案的情况,并处理了编码问题,以避免字符错误。
摘要由CSDN通过智能技术生成

jsonl文件格式示例:

{'ab8145f6d1ee0d7a7a1a2730d50105c0645c21e663767754ef5eba85cf41ddc1': 'Stadacona.'}
{'3a72ecafa9cc526ec3a44a6230aaa7e243e319d2212015b207582ae9c65f9705': 'Stadacona.'}

需要转化为如下格式json文件:
格式1:

{
  "ab8145f6d1ee0d7a7a1a2730d50105c0645c21e663767754ef5eba85cf41ddc1": "Stadacona.",
  "3a72ecafa9cc526ec3a44a6230aaa7e243e319d2212015b207582ae9c65f9705": "Stadacona."
}

格式2:

[
    {
        "ab8145f6d1ee0d7a7a1a2730d50105c0645c21e663767754ef5eba85cf41ddc1": "Stadacona."
    },
    {
        "3a72ecafa9cc526ec3a44a6230aaa7e243e319d2212015b207582ae9c65f9705": "Stadacona."
    }
]

转化为格式1的代码:(需要注意的是,读取文件和写入文件的encoding需要指定为一致,不然会导致gbk和utf混用,导致评测和微调的时候出现字符错误)

import json

def jsonl_to_json(jsonl_file, json_file):
    with open(jsonl_file, 'r', encoding='utf-8') as f:
        jsonl_data = f.readlines()
    # print(jsonl_data)
    # print(jsonl_data[0])
    # print(jsonl_data[0][1:-2])
    # print(jsonl_data[14])

    with open(json_file, 'w', encoding='utf-8') as f:
        for line in jsonl_data:
            line = line[1:-2]
            f.write('    ' + line + ',' + '\n')
    f.close()


jsonl_file = 'C:/Users/Desktop/1.jsonl'
json_file = 'C:/Users/Desktop/test.json'
jsonl_to_json(jsonl_file, json_file)

如果json文件的anwer有多个答案,如:

{'afec84fa0ca103df7b548b9d6a9c33d916ee6464f6585b836bb076e4cdeb8d0b': 'Great Lakes, Pacific Ocean, Atlantic Ocean.'}
{'f492297aef364879271558f8f334d261b4c513357f52bd3c89265d30865eb03f': 'Candy cane, Sprint car racing, ice cream cone, Thanksgiving.'}

那么需要用如下代码转换:

import json

def jsonl_to_json(jsonl_file, json_file):
    converted_items = {}
    with open(jsonl_file, 'r', encoding='utf-8') as f:
        for line in f:
            try:
                item = eval(line)
            except json.decoder.JSONDecodeError:
                print(line)
                return
            pid = list(item.keys())[0]
            print(pid)
            answer = item[pid]
            answers = answer.replace(".", "").split(", ")
            converted_items[pid] = answers

    with open(json_file, 'w', encoding='utf-8') as f:
        json.dump(converted_items, f)


jsonl_file = 'C:/Users/Desktop/epoch_13_KoRC_outputs.jsonl'
json_file = 'C:/Users/Desktop/iid.json'
jsonl_to_json(jsonl_file, json_file)

转化为格式2的代码:(注意需要将jsonl的’转化为”)

import json

def jsonl_to_json(jsonl_file, json_file):
    json_data = []
    with open(jsonl_file, 'r', encoding='utf-8') as f:
        for line in f:
            try:
                obj = json.loads(line)
                json_data.append(obj)
            except json.JSONDecodeError:
                print(f"Ignoring invalid JSON object: {line}")

    with open(json_file, 'w', encoding='utf-8') as f:
        json.dump(json_data, f, indent=4)

jsonl_file = 'C:/Users/Desktop/1.jsonl'
json_file = 'C:/Users/Desktop/test.json'
jsonl_to_json(jsonl_file, json_file)
  • 7
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
回答: 要读取和修改JSON文件的格式,可以使用Pythonjson模块。首先,可以使用open函数打开JSON文件,并使用json.load函数将文件内容加载为Python字典或列表。然后,可以对字典或列表进行修改。最后,可以使用json.dump函数将修改后的内容写回到JSON文件中。以下是一个示例代码: ```python import json # 打开JSON文件并加载内容为字典 with open('data.json', 'r') as f: data = json.load(f) # 修改字典中的内容 data\['key'\] = 'value' # 将修改后的内容写回JSON文件 with open('data.json', 'w') as f: json.dump(data, f) ``` 在这个示例中,我们首先使用open函数打开名为data.jsonJSON文件,并使用json.load函数将文件内容加载为一个字典。然后,我们修改了字典中的某个键值对。最后,我们使用json.dump函数将修改后的内容写回到data.json文件中。请注意,这只是一个简单的示例,实际操作中可能需要根据具体的JSON文件结构进行相应的修改。 #### 引用[.reference_title] - *1* [使用 Python 读取 json 格式文件并查重](https://blog.csdn.net/w_naKing/article/details/126307409)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* *3* [【Python】使用Python读取JSON文件中的内容](https://blog.csdn.net/jylsrnzb/article/details/131458092)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值