объединить и записать два файла jsonl (json строк) в новый файл jsonl в python3 .6 - PullRequest
2 голосов
/ 27 мая 2020

Здравствуйте, у меня есть два jsonl файла, например:

one.jsonl

{"name": "one", "description": "testDescription...", "comment": "1"}
{"name": "two", "description": "testDescription2...", "comment": "2"}

second.jsonl

{"name": "eleven", "description": "testDescription11...", "comment": "11"}
{"name": "twelve", "description": "testDescription12...", "comment": "12"}
{"name": "thirteen", "description": "testDescription13...", "comment": "13"}

И моя цель - написать имя нового jsonl файла (с сохраненной кодировкой) merged_file.jsonl, которое будет выглядеть так:

{"name": "one", "description": "testDescription...", "comment": "1"}
{"name": "two", "description": "testDescription2...", "comment": "2"}
{"name": "eleven", "description": "testDescription11...", "comment": "11"}
{"name": "twelve", "description": "testDescription12...", "comment": "12"}
{"name": "thirteen", "description": "testDescription13...", "comment": "13"}

Мой подход такой:

import json
import glob

result = []
for f in glob.glob("folder_with_all_jsonl/*.jsonl"):
    with open(f, 'r', encoding='utf-8-sig') as infile:
        try:
            result.append(extract_json(infile)) #tried json.loads(infile) too
        except ValueError:
            print(f)

#write the file in BOM TO preserve the emojis and special characters
with open('merged_file.jsonl','w', encoding= 'utf-8-sig') as outfile:
    json.dump(result, outfile)

Однако я встретил эта ошибка: TypeError: Object of type generator is not JSON serializable Я буду признателен за вашу подсказку / помощь любыми способами. Спасибо! Я просмотрел другие репозитории SO, все они пишут обычные json файлы, которые должны работать и в моем случае, но все равно не работают.

Чтение одного файла, как это работает:

data_json = io.open('one.jsonl', mode='r', encoding='utf-8-sig') # Opens in the JSONL file
data_python = extract_json(data_json)
for line in data_python:
    print(line)

####outputs####
#{'name': 'one', 'description': 'testDescription...', 'comment': '1'}
#{'name': 'two', 'description': 'testDescription2...', 'comment': '2'}

Ответы [ 2 ]

3 голосов
/ 27 мая 2020

Возможно, что extract_ json возвращает генератор вместо list / dict, который является json сериализуемым
, поскольку это jsonl, что означает, что каждая строка является действительной json
, поэтому вы просто вам нужно немного подправить существующий код. * все строки

вы можете собрать все строки за один снимок, как это

outfile = open('merged_file.jsonl','w', encoding= 'utf-8-sig')
for f in glob.glob("folder_with_all_jsonl/*.jsonl"):
    with open(f, 'r', encoding='utf-8-sig') as infile:
        for line in infile.readlines():
            outfile.write(line)
outfile.close()
2 голосов
/ 27 мая 2020

еще один очень простой способ сделать это, если вас не волнует json проверка

cat folder_with_all_jsonl/*.jsonl > merged_file.jsonl
...