如何将包含列表字符串的字节转换为Python对象?

blu*_*173 1 python json python-3.x python-3.7

我有一个bytes_start包含列表字符串的字节对象,我想将其转换为 Python 对象。

bytes_start = b'"[{\\"method\\": \\"NULLABLE\\", \\"title\\": \\"Customer\\", \\"type\\": \\"STRING\\"}, {\\"method\\": \\"NULLABLE\\", \\"title\\": \\"Vendor\\", \\"type\\": \\"INTEGER\\"}]"'
Run Code Online (Sandbox Code Playgroud)

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

new_bytes_start = [{"method": "NULLABLE", "title": "Customer", "type": "INTEGER"}, {"method": "NULLABLE", "title": "Vendor", "type": "FLOAT"}]
Run Code Online (Sandbox Code Playgroud)

Mar*_*ers 5

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

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

import json

new_bytes_start = json.loads(json.loads(bytes_start))
Run Code Online (Sandbox Code Playgroud)

演示:

>>> 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'}]
Run Code Online (Sandbox Code Playgroud)

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

new_bytes_start = json.loads(json.loads(bytes_start.decode('utf8')))
Run Code Online (Sandbox Code Playgroud)