JSON序列化自定义非可序列化对象的常规方法是子类化json.JSONEncoder,然后将自定义编码器传递给转储.
它通常看起来像这样:
class CustomEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, foo):
return obj.to_json()
return json.JSONEncoder.default(self, obj)
print json.dumps(obj, cls = CustomEncoder)
Run Code Online (Sandbox Code Playgroud)
我正在尝试做的是使用默认编码器进行序列化.我环顾四周但找不到任何东西.我的想法是编码器会看到一些字段来确定json编码.类似的东西__str__.也许是一个__json__领域.在python中有这样的东西吗?
我想制作一个模块的类,我正在使用JSON序列化给使用该软件包的每个人,而不必担心实现他们自己的[普通]自定义编码器.
我正在尝试编码包含字符串的字典json,并获得一个is not JSON serializable error.
示例代码:
import base64
import json
data={}
encoded = base64.encodebytes(b'data to be encoded')
data['bytes']=encoded
print(json.dumps(data))
Run Code Online (Sandbox Code Playgroud)
我收到的错误:
TypeError: b'ZGF0YSB0byBiZSBlbmNvZGVk\n' is not JSON serializable
Run Code Online (Sandbox Code Playgroud)
如何正确编码包含JSON字节的字典?
我需要决定一个将二进制元素包含到消息对象中的模式,以便可以在接收端再次解码它(在我的情况下是 Rabbit MQ / AMQP 队列上的消费者)。
我决定不使用 JSON 进行多部分 MIME 编码,主要是因为它看起来像是使用雷神之锤来推图钉。我决定不手动连接各个部分(二进制和 JSON 连接在一起),主要是因为每次出现新需求时都需要进行整体重新设计。在其中一个字段中编码二进制文件的 JSON 似乎是一种优雅的解决方案。
我看似可行的解决方案(通过比较发送和接收数据的 MD5 和来确认)解决方案执行以下操作:
def json_serialiser(byte_obj):
if isinstance(byte_obj, (bytes, bytearray)):
# File Bytes to Base64 Bytes then to String
return base64.b64encode(byte_obj).decode('utf-8')
raise ValueError('No encoding handler for data type ' + type(byte_obj))
def make_msg(filename, filedata):
d = {"filename": filename,
"datalen": len(filedata),
"data": filedata}
return json.dumps(d, default=json_serialiser)
Run Code Online (Sandbox Code Playgroud)
在接收端我只需这样做:
def parse_json(msg):
d = json.loads(msg)
data = d.pop('data')
return base64.b64decode(data), d
def file_callback(ch, method, properties, body):
filedata, fileinfo = parse_json(body) …Run Code Online (Sandbox Code Playgroud) 我刚刚完成了霍夫曼压缩算法的创建。我使用 bytearray() 将压缩文本从字符串转换为字节数组。我正在尝试解压缩我的霍夫曼算法。但我唯一担心的是我无法将字节数组转换回字符串。是否有任何内置函数可以用来将我的字节数组(带有变量)转换回字符串?如果没有,是否有更好的方法将我的压缩字符串转换为其他内容?我尝试使用 byte_array.decode() 并得到以下结果:
print("Index: ", Index) # The Index
# Subsituting text to our compressed index
for x in range(len(TextTest)):
TextTest[x]=Index[TextTest[x]]
NewText=''.join(TextTest)
# print(NewText)
# NewText=int(NewText)
byte_array = bytearray() # Converts the compressed string text to bytes
for i in range(0, len(NewText), 8):
byte_array.append(int(NewText[i:i + 8], 2))
NewSize = ("Compressed file Size:",sys.getsizeof(byte_array),'bytes')
print(byte_array)
print(byte_array)
print(NewSize)
x=bytes(byte_array)
x.decode()
Run Code Online (Sandbox Code Playgroud)
UnicodeDecodeError:“utf-8”编解码器无法解码位置 0 中的字节 0x88:起始字节无效
尝试将输出转换为 Json 格式但出现错误。删除 json.dump 后,将数据转换为 Base64 格式。但是当使用 json.dump 时它显示错误。
代码:
import json
import base64
with open(r"C:/Users/Documents/pdf2txt/outputImage.jpg","rb") as img:
image = base64.b64encode(img.read())
data['ProcessedImage'] = image
print(json.dump(data)
Run Code Online (Sandbox Code Playgroud)
输出:
TypeError: Object of type 'bytes' is not JSON serializable
Run Code Online (Sandbox Code Playgroud)
使用时:
print(json.dumps(dict(data)))
Run Code Online (Sandbox Code Playgroud)
它也显示相同的错误
我有数据(主要是一系列 numpy 数组),我想将其转换为可以复制/粘贴/通过电子邮件发送等的文本。我创建了以下公式来执行此操作。
def convert_to_ascii85(x):
p = pickle.dumps(x)
p = zlib.compress(p)
return b64.b85encode(p)
Run Code Online (Sandbox Code Playgroud)
我的问题是它产生的字符串比它需要的要长,因为它只使用字母、数字和符号的子集。如果我能够使用 unicode 进行编码,我觉得它可以产生更短的字符串,因为它可以访问更多字符。有没有办法做到这一点?
编辑澄清:我的目标不是最小数量的 data/information/bytes。我的目标是最少的字符数。原因是我发送数据的通道以字符(准确地说是 100k)而不是字节(奇怪,我知道)为上限。我已经测试过我可以发送 100k unicode 字符,我只是不知道如何将我的字节转换为 unicode。
如何将 bytes 类型数组转换为 str 或 json?我有这个 python 字节码,我需要转换为 json 格式或字符串格式。我怎样才能做到这一点?
b'x\xda\x04\xc0\xb1\r\xc4 \x0c\x85\xe1]\xfe\x9a\x06\xae\xf36\'B\x11\xc9J$?\xbbB\xec\x9eo\xb3"\xde\xc0\x9ero\xc4Ryb\x1b\xe5?K\x18\xaa9\x97\xc4i\xdc\x17\xd6\xc7\xaf\x8f\xf3\x05\x00\x00\xff\xff l\x12l'
Run Code Online (Sandbox Code Playgroud) 我正在通过 pandas.read_csv() 读取 CSV 文件。当指定 enconding = UTF-8 或 16 时,会出现错误。
“utf-8”编解码器无法解码位置 127 中的字节 0xa3:起始字节无效
我的疑问是,当UTF是多字节编码而latin1是单字节编码时,为什么我在使用UTF-8或16时会出现错误,但使用latin1却可以正常工作?UTF不应该更优越并且可以解码所有字符吗?
提前致谢。
尝试编码= latin1,'cp1252','iso-8859-15'
python ×8
json ×5
arrays ×2
base64 ×2
encoding ×2
python-3.x ×2
binary-data ×1
compression ×1
decode ×1
encode ×1
huffman-code ×1
pandas ×1
utf-8 ×1