What is the official way to save list of dictionaries and jsonl or json lines? I saw: https://ml-gis-service.com/index.php/2022/04/27/toolbox-python-list-of-dicts-to-jsonl-json-lines/ with solution:
import gzip
import json
def dicts_to_jsonl(data_list: list, filename: str, compress: bool = True) -> None:
"""
Method saves list of dicts into jsonl file.
:param data: (list) list of dicts to be stored,
:param filename: (str) path to the output file. If suffix .jsonl is not given then methods appends
.jsonl suffix into the file.
:param compress: (bool) should file be compressed into a gzip archive?
"""
sjsonl = '.jsonl'
sgz = '.gz'
# Check filename
if not filename.endswith(sjsonl):
filename = filename + sjsonl
# Save data
if compress:
filename = filename + sgz
with gzip.open(filename, 'w') as compressed:
for ddict in data:
jout = json.dumps(ddict) + '\n'
jout = jout.encode('utf-8')
compressed.write(jout)
else:
with open(filename, 'w') as out:
for ddict in data:
jout = json.dumps(ddict) + '\n'
out.write(jout)
but feels weird to copy paste code to do this or that no other stack overflow question asks this already or the original/official json library doesn't seem to reference this?