How to replace value in a JSON file? [closed]

Solution 1:

replace

x['gw_status'] = x['gw_status'].replace('ongoing', x['completed'])

with

x['gw_status'] = 'completed'

after changing this Your code will look like

with open ('gw.json') as json_file:
    data = json.load(json_file)

    new_gw = {
      'gw_id': f"{react_id}",
      'gw_prize': prize,
      'gw_status': "ongoing"
    }

    data.append(new_gw)

    with open('gw.json', 'w') as j:
      json.dump(data, j, indent=4)

    #some other stuff

    #when completed

    with open ('gw.json', 'r') as jsonFile:
      data = json.load(jsonFile)
      for x in data:
        if x['gw_id'] == f"{msgid}":
          x['gw_status'] = 'completed' #change the value of 'gw_status' when completed
      with open ('gw.json', 'w') as jsonFile:
        json.dump(data, jsonFile)

gw.json file before running the code

[
  { "gw_id": "id", 
    "gw_prize": "prize", 
    "gw_status": "ongoing" 
    }
]

gw.json file after running the code

[
  { "gw_id": "id", 
    "gw_prize": "prize", 
    "gw_status": "ongoing" 
    },
  {
    "gw_id": "904905768149590086",
    "gw_prize": "tdd",
    "gw_status": "completed"
  }
]