0

How to create a null json file and append each details to the json file in the following format

[ 
   {"name":"alan","job":"clerk"},
   {"name":"bob","job":"engineer"}
]

Code

import json
with open("test.json", mode='w', encoding='utf-8') as f:
    json.dump([], f)

test_data = ['{"name":"alan","job":"clerk"}','{"name":"bob","job":"engineer"}']
for i in test_data:
    with open("test.json", mode='w', encoding='utf-8') as fileobj:
        json.dump(i, fileobj)

How this can be efficiently done

1
  • You can't "append" data directly to the json file. You need to prepare the data in the appropriate format and dump it once. When you do json.dump([], f) you literally write [] to the file. Why not just do json.dump([{"name":"alan","job":"clerk"}, {"name":"bob","job":"engineer"}], fileobj)? Commented Sep 9, 2021 at 15:00

1 Answer 1

1

You can't modify the json content like that. You'll need to modify the data structure and then completely rewrite the json file. You might be able to just read the data from jsone at startup, and write it at shutdown.

import json

def store_my_data(data, filename='test.json'):
    """ write data to json file """
    with open(filename, mode='w', encoding='utf-8') as f:
        json.dump(data, f)

def load_my_data(filename='test.json'):
    """ load data from json file """
    with open(filename, mode='r', encoding='utf-8') as f:
        return json.load(f)
    raise Exception # skipping some steps here

test_data = [
   {"name": "alan", "job": "clerk"},
   {"name": "bob", "job": "engineer"}
]
item_one = test_data[0]
item_two = test_data[1]

# You already know how to store data in a json file.
store_my_data(test_data)

# Suppose you don't have any data at the start.
current_data = []
store_my_data(current_data)

# Later, you want to add to the data.
# You will have to change your data in memory, 
# then completely rewrite the file.
current_data.append(item_one)
current_data.append(item_two)
store_my_data(current_data)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.