Search code examples
pythonjsonjson-value

modifiy data of json file


How can I modify the values of json file using python? so my json file is:

{
  "roll no": "210",
  "school": "DAP",
  "city": "Delhi",
  "hobbies": [
    {
      "dance": "yes"
    },
 {
      "singing": "yes"
    },
 {
      "travel": "yes"
    },
            ]
}

so this is my json and I want to replace the values like: roll no= 211 and travel="no" ,singing="no"

I have tried:

with open("student.json","r") as file:
    data=json.load(file)
    data["roll no"]= "211"
    
    for x in data:
        x["hobbies"]["singing"]="no"
        x["hobbies"]["travel"]="no"

            
        with open("student.json","w") as file:

        json.dump(data,file,indent=4)

I have tried this but the only change I'm able to doing is roll no,but I'm unable to change the hobbies values expected output:

{
  "roll no": "211",
  "school": "DAP",
  "city": "Delhi",
  "hobbies": [
    {
      "dance": "yes"
    },
 {
      "singing": "no"
    },
 {
      "travel": "no"
    },
            ]
}

Solution

  • Here is how i have updated hobbies for new roll number

    import json
    
    json_data = '''{
      "roll no": "210",
      "school": "DAP",
      "city": "Delhi",
      "hobbies": [
        {
          "dance": "yes"
        },
     {
          "singing": "yes"
        },
     {
          "travel": "yes"
        }
                ]
    }
    '''
    
    data = json.loads(json_data)
    
    data["roll no"] = "211"
    for hobby in data["hobbies"]:
        for upd_hobby in ["singing", "travel"]:
            if upd_hobby in hobby:
                hobby[upd_hobby] = "no"
    
    print(json.dumps(data, indent=4))
    

    Output:

    {
        "roll no": "211",
        "school": "DAP",
        "city": "Delhi",
        "hobbies": [
            {
                "dance": "yes"
            },
            {
                "singing": "no"
            },
            {
                "travel": "no"
            }
        ]
    }