Home > Software engineering >  modifiy data of json file
modifiy data of json file

Time:01-11

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"
    },
            ]
}

CodePudding user response:

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

CodePudding user response:

'hobbies' is a list of dict so you should write:

with open("student.json", "r") as file:
    data = json.load(file)

data["roll no"] = "211"
data["hobbies"][1]["singing"] = "no"
data["hobbies"][2]["travel"] = "no"

        
with open("student.json","w") as file:
    json.dump(data, file, indent=4)

CodePudding user response:

As i said in above comment, you will get an error while passing index as string to list.

See below code

with open("./students.json", "r") as file:
  data = json.load(file)

Methode 1 (If the hobbies are hardcoded)

data["roll no"] = "211"
data["hobbies"][1]["singing"] = "no"
data["hobbies"][2]["travel"] = "no"

Method 2 (if you want to dynamically include some hobbies to change their state 'yes' - 'no')

hobbies_inc = ["singing", "travel"] # Create a list hobbies, that need to be included

for x in data["hobbies"]:
   if list(x)[0] in hobbies_inc:
        x[list(x)[0]] = "no"
 
  • Related