[英]How to fix the str problem with json.dumps please?
Hello, could someone helps me with this please? 您好,有人可以帮我这个吗?
import json
import urllib.request
from urllib.request import urlopen
postdata = {
'datetime': str(calendar.timegm(time.gmtime())),
'sensorId': "1",
'tempRecord': str(read_temp())
}
req = Request(url)
req.add_header('Content-Type','application/json')
data = json.dumps(postdata)
response = urlopen(req,data)
You should use: 你应该使用:
response = urlopen(req, data.encode())
Why? 为什么?
Because json.dump(postdata)
returns a str object, 因为json.dump(postdata)
返回一个str对象,
whereas urlopen
expects a bytes
object. 而urlopen
需要一个bytes
对象。
So you have to convert data
from str
to bytes
, and you do this using encode
. 因此,您必须将data
从str
转换为bytes
,并使用encode
执行此操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.