python - 如何将包含列表字符串的字节转换为 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"}]
解决方案
您的 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')))
推荐阅读
- asp.net-mvc - DataTable 上选择选项的下拉列表效果不佳,如何在我的 JqueryUI 上解决此问题?
- datetime - 如何更改 sqflite 数据库中的日期时间格式,使其仅显示日期?
- javascript - 在 React 中实现动态输入数组的最佳方法
- ruby-on-rails - 嵌套表单未显示在页面上
- c# - .NET 模型项目显示在输入框中,但不在链接中
- mongodb - Spring Data Mongo DB:回复消息长度5502322小于最大消息长度
- r - Shiny:加入 R 中的单元格
- python - 无法在 __init__.py 中导入定义的模块
- unity3d - 为什么这里需要 StartCorotine()
- python - Python3类中的继承