giantmario
giantmario

Reputation: 35

How to dump Python data into already made JSON folder?

I started to learn more about json and dumping data into a json file with python. My question is: I made two json files not with python code (with open("randomFile.json") but I made the files 'with hand' and I stored one value to each file and loaded those values into separate variables.. Now I modified the variables(values) from json file inside a program and now I want to store or replace the old values with the new modified values inside these already made json files.. I hope this makes sense. Here is a simple example code..


import json

f1 = open('number1.json')
number1 = json.load(f1)

f2 = open('number2.json')
number2 = json.load(f2)

number1 += 10

number2 += 5

So variables number1 and number2 got the values from json file now I want to store these new values into the same json file..

Upvotes: 0

Views: 87

Answers (1)

hysoftwareeng
hysoftwareeng

Reputation: 497

Suppose you have the following valid json file called number1.json:

{
    "field": 1
}

Then, you can update it with the following code. Just do the same thing for number2.json:

import json
import os

file = 'number1.json'
with open(file, 'r+') as f:
    data = json.load(f)
    data['field'] += 10

os.remove(file)
with open(file, 'w') as f:
    json.dump(data, f, indent=4)

EDIT: As mentioned in the comments, in this simple case, you can also modify without removing the file:

import json
import os

file = 'number1.json'
with open(file, 'r+') as f:
    data = json.load(f)
    data['field'] += 10
    f.seek(0)
    json.dump(data, f, indent=4)

Upvotes: 1

Related Questions