简体   繁体   中英

Python: Writing and updating a .json file from Dictionary

I am generating a dictionary and I want to write it in a .json file. Lets say I have the following code:

data = []
sample = {'Value 1': 16,  'Value 2': 1, 'Value 3': 2}
sample2 = {'Value 1': 10,  'Value 2': 1, 'Value 3': 2,'Value 4':[1,4]}
data.append(sample)
data.append(sample2)

I want to write data to a json format file to different lines. Something like this:

在此处输入图片说明

I am using the following code:

with open('trial.json', 'w') as fp:
    json.dump(data, fp)

But this writes a file all in one line. How do I write it in order to be in different lines?

Furthermore, assuming that I have the file above in different lines: how can I update it? For example I want to insert a new row:

sample3 = {'Value 1': 1,  'Value 2': 8, 'Value 3': 4}

What code should I write to insert this to the same file without erasing the previous data? So to be like this:

在此处输入图片说明

Using the previous code block erasies the previous data.

Edit: A way to 'update' the file(not the most elegant) is the following:

with open('trial.json', 'w',encoding='utf-8') as fp:
    json.dump(data, fp)


sample3 = {'Value 1': 1,  'Value 2': 8, 'Value 3': 4}

with open('trial.json', mode='r', encoding='utf-8') as feedsjson:
    feeds = json.load(feedsjson)

with open('trial.json','w',encoding='utf-8') as feedsjson:
    feeds.append(sample3)
    json.dump(feeds,feedsjson)

It can be seen that I am not using the indent option. An error pop-ups if I use it.

You need to do this:

with open('trial.json', 'w') as fp:
    json.dump(data, fp, indent=2)

It will ask the json.dump to prettify your json encoded text.

import json 
#SAMPLE_FILE.JSON
{'Value 1': 16,  'Value 2': 1, 'Value 3': 2}
a_file = open("sample_file.json", "r")
json_object = json.load(a_file)
a_file.close()
print(json_object)
OUTPUT
{'a': {'b': 1, 'c': 2}, 'd': 3}

json_object["Value 4"] = [1,4]

a_file = open("sample_file.json", "w")
json.dump(json_object, a_file)
a_file.close()
#SAMPLE_FILE.JSON
{'Value 1': 10,  'Value 2': 1, 'Value 3': 2,'Value 4':[1,4]}

More details here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM