Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to json.dumps byte object in python3

In python2

import json
a = {"text": u"你好".encode("gbk")}
json.dumps(a, ensure_ascii=False)

>>> Out: '{"text": "\xc4\xe3\xba\xc3"}'

I want to get same 'Out' in python3:

import codecs
byte_obj = "你好".encode("gbk")
x = byte_obj.decode("utf8", "backslashreplace") # ops, it become '\\xc4\\xe3\\xba\\xc3'
x = codecs.escape_encode(byte_obj)[0] # ops, it become b'\\xc4\\xe3\\xba\\xc3'

# fail, I have to concatenate them

b'{"text": "' + u"你好".encode("gbk") + b'"}'

>>> Out: b'{"text": "\xc4\xe3\xba\xc3"}'

In Python3, If there is a way to convert

{"text": "你好"}  # first, encoding with gbk, then json.dumps 

to

b'{"text": "\xc4\xe3\xba\xc3"}'  # json serialized result
like image 393
郭泽平 Avatar asked Jun 09 '17 04:06

郭泽平


1 Answers

If you actually want GBK encoding in Python 3:

import json
a = {"text": u"你好"}
print(json.dumps(a, ensure_ascii=False).encode('gbk'))

b'{"text": "\xc4\xe3\xba\xc3"}'

like image 98
Mark Tolonen Avatar answered Oct 14 '22 09:10

Mark Tolonen