How to create a JSON file in Python

Introduction

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 image.png

Implementation policy

--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]

Implementation example

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"
    ]
}
]

reference

Official documentation

At the end

Please let me know if there is a better way to write

Recommended Posts

How to create a JSON file in Python
Create a binary file in Python
How to create a config file
Python script to create a JSON file from a CSV file
Create a JSON object mapper in Python
How to import a file anywhere you like in Python
How to get a stacktrace in python
[GPS] Create a kml file in Python
How to create a heatmap with an arbitrary domain in Python
How to read a CSV file with Python 2/3
Create a GIF file using Pillow in Python
How to create a Python virtual environment (venv)
How to clear tuples in a list (Python)
How to embed a variable in a python string
How to generate a Python object from JSON
How to notify a Discord channel in Python
[Python] How to draw a histogram in Matplotlib
How to create a Rest Api in Django
Create a MIDI file in Python using pretty_midi
How to read a file in a different directory
Create a function in Python
Create a dictionary in Python
How to develop in Python
How to convert / restore a string with [] in python
[Python] How to expand variables in a character string
Create a plugin to run Python Doctest in Vim (2)
Create a plugin to run Python Doctest in Vim (1)
A memorandum to run a python script in a bat file
I want to randomly sample a file in Python
How to convert JSON file to CSV file with Python Pandas
How to create an image uploader in Bottle (Python)
[Work efficiency] How to change file names in Python
[Python] How to create a 2D histogram with Matplotlib
How to execute a command using subprocess in Python
How to create a kubernetes pod from python code
How to handle JSON in Ruby, Python, JavaScript, PHP
How to write a Python class
I tried to create a class that can easily serialize Json in Python
Create a DI Container in Python
How to collect images in Python
How to use SQLite in Python
How to drop Google Docs in one folder in a .txt file with python
How to create a Conda package
How to create a virtual bridge
How to use Mysql in python
How to wrap C in Python
How to use ChemSpider in Python
How to create a Dockerfile (basic)
How to use PubChem in Python
Create a Kubernetes Operator in Python
5 Ways to Create a Python Chatbot
Create a random string in Python
How to handle Japanese in Python
How to slice a block multiple array from a multiple array in Python
How to run a Python file at a Windows 10 command prompt
How to use the __call__ method in a Python class
How to define multiple variables in a python for statement
[Python Kivy] How to create a simple pop up window
I tried "How to get a method decorated in Python"
How to develop in a virtual environment of Python [Memo]
How to get the last (last) value in a list in Python