H
H
hoojpop2021-04-21 17:44:52
Python
hoojpop, 2021-04-21 17:44:52

How to update certain data in JSON?

There is a JSON file. In which the following data:

{"_TIMES": "1", "RunestoneRare": 0, "EssenceRare": 0, "DustRare": 0, "RunestoneEpic": 0, "EssenceEpic": 0, "DustEpic": 0, "RunestoneLegendary": 0, "EssenceLegendary": 0, "DustLegendary": 0, "Ruby": 0}


There is a code where I check the value REWARDSfor the match of a word from JSON and want to add +1 to the value:

import json
    
    REWARD = 'RunestoneRare'
    i = 0
    
    REWARDS = {
        "_TIMES":"1", 
        "RunestoneRare":0, 
        "EssenceRare":0, 
        "DustRare":0, 
        "RunestoneEpic":0, 
        "EssenceEpic":0, 
        "DustEpic":0, 
        "RunestoneLegendary":0, 
        "EssenceLegendary":0, 
        "DustLegendary":0, 
        "Ruby": 0
    }
    
    to_json = REWARDS
    
    with open('sw_templates.json', 'w') as f:
        f.write(json.dumps(to_json))
    
    with open('sw_templates.json', 'r') as f:
        if REWARD == 'RunestoneRare':
            json_data = json.load(f)
            print(json_data['RunestoneRare'])
            json_data['RunestoneRare'] = i + 1
    
    with open('sw_templates.json', 'w') as f:
        f.write(json.dumps(json_data))

---

At the first execution of the code, the value 1 appears in `RunestoneRare`, as if it pleases, but at the second execution, the value is the same.

Tried: ++i, json_data['RunestoneRare'] += 1, json_data['RunestoneRare'] = i + 1- Does not help.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
Y
Yupiter7575, 2021-04-21
@hoojpop

You don't have a loop here => you start the program again every time =>

REWARDS = {
"_TIMES":"1",
"RunestoneRare":0,
"EssenceRare":0,
"DustRare":0,
"RunestoneEpic":0,
"EssenceEpic":0,
"DustEpic":0,
"RunestoneLegendary" :0,
"EssenceLegendary":0,
"DustLegendary":0,
"Ruby": 0
}

this is done every time

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question