简体   繁体   English

如何解决json.dumps的str问题?

[英]How to fix the str problem with json.dumps please?

Hello, could someone helps me with this please? 您好,有人可以帮我这个吗?

TypeError: POST data should be bytes or an iterable of bytes. TypeError:POST数据应该是字节或可迭代的字节。 It can not be of type str. 它不能是str类型。

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 . 因此,您必须将datastr转换为bytes ,并使用encode执行此操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM