Python's json module can read JSON files and write JSON-formatted objects, but it cannot create JSON files. I implemented the JSON file creation as needed, so I will leave it as a memo.
From the official document https://docs.python.org/ja/3/library/json.html
--Insert [If the JSON file you want to write is empty --Insert JSON format object --Insert [at the end] --The next time you insert it, replace it with, if it ends in]
The following 3 files are assumed to be in the same hierarchy
json_make.py
import json
from pathlib import Path
def json_make(path: Path, obj: dict) -> None:
ls = None
with open(path, 'r+') as f:
ls = f.readlines()
if ls == []:
ls.append('[\n')
if ls[-1] == ']':
ls[-1] = ','
ls.insert(len(ls), f'{json.dumps(obj, indent=4 ,ensure_ascii=False)}')
ls.insert(len(ls), '\n]')
with open(path, 'w') as f:
f.writelines(ls)
main.py
from json_make import json_make
from pathlib import Path
def main():
path = Path(__file__).parent/'tmp.json'
dict_obj = {'key1':'value1', 'key2':'value2', 'key3':['value3', 'value4']}
json_make(path, dict_obj)
if __name__ == '__main__':
main()
For json.dumps (indent = 0)
tmp.json
[
{"key1": "value1", "key2": "value2", "key3": ["value3", "value4"]}
,{"key1": "value1", "key2": "value2", "key3": ["value3", "value4"]}
,{"key1": "value1", "key2": "value2", "key3": ["value3", "value4"]}
,{"key1": "value1", "key2": "value2", "key3": ["value3", "value4"]}
]
For json.dumps (indent = 4)
tmp.json
[
{
"key1": "value1",
"key2": "value2",
"key3": [
"value3",
"value4"
]
}
,{
"key1": "value1",
"key2": "value2",
"key3": [
"value3",
"value4"
]
}
,{
"key1": "value1",
"key2": "value2",
"key3": [
"value3",
"value4"
]
}
,{
"key1": "value1",
"key2": "value2",
"key3": [
"value3",
"value4"
]
}
]
Please let me know if there is a better way to write
Recommended Posts