将python 2.7x代码移植到python 3.7x时,Python3 JSON编码错误“没有编码的字符串参数” >> [

问题描述 投票:0回答:1
我正在将python 2.7x代码移植到python 3.7x。此代码尝试使用TCP套接字将一些数据发布到服务器。创建JSON.dumps(data)时出现编码错误。

try: sei_nal_unit = create_sei_nal_unit(camera_config.SEI_UUID_CAMERA_SETTINGS, json.dumps(capture_settings) ) #connection_filehandle.write(sei_nal_unit) except Exception as e: log.write("socket Thread TCP - exception in sending data [%s]" % (str(e)) ) def encode_multibyte_value(value): """ encode values >= 255 as 0xff0xff..0xresidual """ encoded = bytearray() while (value >= 255): encoded += bytearray(chr(255)) value -= 255 encoded += bytearray(chr(value)) return encoded def escape_bytearray(input): """ escape 000 to 0030, 001 to 0031, 002 to 0032 and 003 to 0033 """ output = bytearray() history1 = None history2 = None for b in input: if (history1==0) and (history2==0) and (b <= 3): output += chr(3) history1 = 3 history2 = b else: history1 = history2 history2 = b output += chr(b) return output def create_sei_nal_unit(uuid, payload_string): """ create a 'user data unregistered' SEI nal unit in a bytearray """ try: assert(bytearray == type(uuid)) uuid_length = len(uuid) assert(16 == uuid_length) nal_unit_prefix = bytearray(b'\x00\x00\x00\x01') nal_unit_type = bytearray(chr(6)) # 6 = SEI encoded_payload_type = encode_multibyte_value(5) # 5 = 'user data unregistered' payload = bytearray(payload_string) encoded_payload_size = encode_multibyte_value(uuid_length + len(payload)) escaped_payload = escape_bytearray(uuid + payload) trailing_bits = bytearray(b'\x80') sei_nal_unit = ( nal_unit_prefix + nal_unit_type + encoded_payload_type + encoded_payload_size + escaped_payload + trailing_bits ) return sei_nal_unit except Exception as e: print(str(e))

错误是

socket Thread TCP - an exception in sending data [string argument without an encoding]

JSON文件为

capture_settings = [{"framerate": 30, "width": 1280, "height": 720, "bitrate": 17000000, "overlay": false, "gop_size": 30}]

我没有找到任何线索,尽管我尝试了很多方法但没有希望。谢谢高级。

我正在将python 2.7x代码移植到python 3.7x。此代码尝试使用TCP套接字将一些数据发布到服务器。创建JSON.dumps(data)时出现编码错误。尝试:...

json python-3.x python-2.7 http http-post
1个回答
1
投票
json.dumps()调用返回一个字符串。通过TCP套接字发送之前,必须将其编码为bytes。最简单的方法是使用:
© www.soinside.com 2019 - 2024. All rights reserved.