首页 > 解决方案 > 如何将包含列表字符串的字节转换为 Python 对象?

问题描述

我有一个bytes_start包含列表字符串的字节对象,我想把它变成一个 Python 对象。

bytes_start = b'"[{\\"method\\": \\"NULLABLE\\", \\"title\\": \\"Customer\\", \\"type\\": \\"STRING\\"}, {\\"method\\": \\"NULLABLE\\", \\"title\\": \\"Vendor\\", \\"type\\": \\"INTEGER\\"}]"'

我尝试使用new_bytes_start = json.dumps(bytes_start),但没有奏效。如何使用 Python 3 获得以下结果?

new_bytes_start = [{"method": "NULLABLE", "title": "Customer", "type": "INTEGER"}, {"method": "NULLABLE", "title": "Vendor", "type": "FLOAT"}]

标签: pythonjsonpython-3.xpython-3.7

解决方案


您的 bytes 值包含双重编码的JSON 文档。您不需要第三次对此进行编码。

如果您想将数据加载到 Python 对象中,则需要使用以下命令对 JSON 进行两次json.loads()解码:

import json

new_bytes_start = json.loads(json.loads(bytes_start))

演示:

>>> import json
>>> bytes_start = b'"[{\\"method\\": \\"NULLABLE\\", \\"title\\": \\"Customer\\", \\"type\\": \\"STRING\\"}, {\\"method\\": \\"NULLABLE\\", \\"title\\": \\"Vendor\\", \\"type\\": \\"INTEGER\\"}]"'
>>> json.loads(bytes_start)
'[{"method": "NULLABLE", "title": "Customer", "type": "STRING"}, {"method": "NULLABLE", "title": "Vendor", "type": "INTEGER"}]'
>>> json.loads(json.loads(bytes_start))
[{'method': 'NULLABLE', 'title': 'Customer', 'type': 'STRING'}, {'method': 'NULLABLE', 'title': 'Vendor', 'type': 'INTEGER'}]

如果您使用的 Python 版本早于 Python 3.6,您还必须先解码字节串;大概是 UTF-8,此时您将使用:

new_bytes_start = json.loads(json.loads(bytes_start.decode('utf8')))

推荐阅读