Home > Net >  How to change the element value in json format
How to change the element value in json format

Time:09-21

I'd like to change the delivery window value. Here is the original data structure.

{
   "locations":[
      {
         "depot_duration_s":90,
         "depot_id":"depot_1",
         "time_window":"09:00-20:00",
         "type":"delivery"
      },
      {
         "depot_duration_s":90,
         "depot_id":"depot_1",
         "time_window":"09:00-20:00",
         "type":"delivery"
      },
      {
         "depot_duration_s":90,
         "depot_id":"depot_1",
         "time_window":"09:00-20:00",
         "type":"delivery"
      }
   ]
}

Here is the code I tried, but I got "list indices must be integers or slices, not str". Could you let me know how to fix the code here?

import json

with open('C:/Users/8_31_file.json', 'r ', errors = "ignore") as myData:
    myData = json.load(myData)
    mylist = myData["locations"][-2:]
    mylist["time_window"] = "17:00-20:00"
    mylist = {'locations':mylist}
    print(mylist)

CodePudding user response:

You are setting mylist to be a list object. You then try to call mylist["time_window"] which is where the error is coming from. As the error says the index of a list cannot be a str. You probably want something like:

mylist[0]["time_window"] = "17:00-20:00"

You need to know which element of mylist to change though. If you are trying to change all elements then you would need to iterate over mylist like this:

for i in mylist:
    i['time_window'] = "17:00-20:00"

CodePudding user response:

Just to add on @abinitio's answer, you can even simplify your whole logic into this:

with open('C:/Users/8_31_file.json', 'r ', errors = "ignore") as myData:
    myData = json.load(myData)
    for loc in myData["locations"]:
        loc["time_window"] = "17:00-20:00"
    print(myData)
  • Related