Home > Net >  Modify VALUE inside LIST located in JSON DICTIONARY
Modify VALUE inside LIST located in JSON DICTIONARY

Time:09-22

I would like to ask this is my JSON file. if I would like to change my 'c' to '9', how do I write for the data?

{
   'x': 4,
   'y': 5,
   'z': [
     {
       'a': 1, 
       'b': 2, 
       'c': 3
     }
   ]
}
import urllib.request
import json

data = ?????
myurl = "http://192.168.1.10:8888/testJSON"

req = urllib.request.Request(myurl)
req.add_header('Content-Type', 'application/json; charset=utf-8')
jsondata = json.dumps(data)
jsondataasbytes = jsondata.encode('utf-8')   # needs to be bytes
req.add_header('Content-Length', len(jsondataasbytes))
response = urllib.request.urlopen(req, jsondataasbytes)

The Solution provided by @BhagyeshDudhediya is working:

import urllib.request
import json

data['z'][0]['c'] = 9
myurl = "http://192.168.1.10:8888/testJSON"

req = urllib.request.Request(myurl)
req.add_header('Content-Type', 'application/json; charset=utf-8')
jsondata = json.dumps(data)
jsondataasbytes = jsondata.encode('utf-8')   # needs to be bytes
req.add_header('Content-Length', len(jsondataasbytes))
response = urllib.request.urlopen(req, jsondataasbytes)

CodePudding user response:

Just do this: data['z'][0]['c'] = 9

  • Related