How to update exisitng json file with Python?

Question:

I have data.json and read to data variable.

f = open("data.json", "r")
data = np.array(json.loads(f.read()))

ouput of ‘data’ as below.

[{
    "symbol" : "NZDCHF",
    "timeframe" : [
        {"tf":"H4","x1":0,"y1":0,"x2":0,"y2":0},
        {"tf":"H1","x1":0,"y1":0,"x2":0,"y2":0},
        {"tf":"M30","x1":0,"y1":0,"x2":0,"y2":0},
        {"tf":"M15","x1":0,"y1":0,"x2":0,"y2":0},
        {"tf":"M5","x1":0,"y1":0,"x2":0,"y2":0}
      ]  
},
{
    "symbol" : "AUDCHF",
    "timeframe" : [
        {"tf":"H4","x1":0,"y1":0,"x2":0,"y2":0},
        {"tf":"H1","x1":0,"y1":0,"x2":0,"y2":0},
        {"tf":"M30","x1":0,"y1":0,"x2":0,"y2":0},
        {"tf":"M15","x1":0,"y1":0,"x2":0,"y2":0},
        {"tf":"M5","x1":0,"y1":0,"x2":0,"y2":0}
      ]  
}]

I can find some existing value, e.g. ‘AUDCHF’.

selected = np.array([el for el in data if el["symbol"] == 'AUDCHF'])
rect = selected[0]['timeframe'][4]

and the output from above ‘rect’

{"tf":"M5","x1":0,"y1":0,"x2":0,"y2":0}

I would like to update x1, y1, x2 and y2 then dump to file. Any advice or guidance on this would be greatly appreciated, Thanks.

Asked By: joenpc npcsolution

||

Answers:

you don’t need numpy here:

with open("data.json", "r") as f:
    data = json.load(f)
for item in data:
    if item['symbol'] == 'AUDCHF':
        # same for x2 and y2
        item['timeframe'][4]['x1'] = 1
        item['timeframe'][4]['y1'] = 1
        break
else: # this will only trigger if the loop finished without the break being called
    print("symbol 'AUDCHF' not found)
    exit(0)
with open("data_edited.json", "w") as f:
    json.dump(data, f)
Answered By: Nullman
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.