Home > Enterprise >  how to replace value in a json file using python?
how to replace value in a json file using python?

Time:11-02

what i am trying to do is:-

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'] = x['gw_status'].replace('ongoing', x['completed']) #change the value of 'gw_status' when completed
    with open ('gw.json', 'w') as jsonFile:
      json.dump(data, jsonFile)

what i want to do is

[
    {
        "gw_id": "id",
        "gw_prize": "prize",
        "gw_status": "ongoing"
    }
{
        "gw_id": "904905768149590086",
        "gw_prize": "tdd",
        "gw_status": "ongoing" <== this one to be changed to "completed"
    }
]

but the code i wrote doesn't work please help!! i need to complete this till tommorow

It looks like your post is mostly code; please add some more details. It looks like your post is mostly code; please add some more details. It looks like your post is mostly code; please add some more details.

CodePudding user response:

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"
  }
]
  • Related