【发布时间】:2021-09-21 09:37:14
【问题描述】:
我想问一下这是我的 JSON 文件。如果我想将我的 'c' 更改为 '9',我该如何写数据?
{
'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)
@BhagyeshDudhediya 提供的解决方案有效:
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)
【问题讨论】:
-
你想把
'c': 3改成'c': 9吗? -
这是你想要的吗:
data['z'][0]['c'] = 9? -
@Sabil 是的,我想将 'c' 从 3 更改为 9
-
@BhagyeshDudhediya 正确,据我所知,如果我想将 x 从 4 更改为 6,我只需输入 data = { x : 6}。对于 data['z'][0]['c'] 我不知道该怎么做。
-
data['z'][0]['c'] = 9是要走的路。顺便说一句,如果您只想将 x 从 4 更改为 6,则应使用data['x']=6,如果您使用data={x:6},则您的整个字典将被覆盖