您好,我有两个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'}