python - 无法将字节转换为 JSON
问题描述
序列化程序类确保写入数据库的数据是 JSON 格式:
sh_list = serializers.JSONField(binary=True)
数据作为输出 JSON 中的条目之一可见:
...
"sh_list": "\"[{'position': 1, 'item': 'Display'},
{'position': 3, 'item': 'Keyboard'},
{'position': 4, 'item': 'Headphones'}]\"",
...
我在views.py
尝试将数据转换为字典时对其进行处理:
sh_list = json.loads(serializer.data["sh_list"])
print('sh_list:', sh_list)
# sh_list: [{'position': 1, 'item': 'Display'}, {'position': 3, 'item': 'Keyboard'}, {'position': 4, 'item': 'Headphones'}]
print('sh_list type:', type(sh_list))
# sh_list type: <class 'str'>
print('serializer.data["sh_list"] type:', type(serializer.data["sh_list"]))
# serializer.data["sh_list"] type: <class 'bytes'>
sh_list2 = serializer.data["sh_list"].decode()
print('sh_list2:', sh_list2)
# sh_list2: "[{'position': 1, 'item': 'Display'}, {'position': 3, 'item': 'Keyboard'}, {'position': 4, 'item': 'Headphones'}]"
print('sh_list2 type:', type(sh_list2))
# sh_list2 type: <class 'str'>
sh_list3 = json.loads(sh_list2)
print('sh_list3[0]:', sh_list3[0])
# sh_list3[0]: [
print('sh_list3 type:', type(sh_list3))
# sh_list3 type: <class 'str'>
对我来说期望的输出是这样的:
print('sh_list3[0]:', sh_list3[0])
# sh_list3[0]: {'position': 1, 'item': 'Display'}
如何进行从字节到字典的转换?
解决方案
sh_list = json.loads(serializer.data["sh_list"])
返回一个字典。
一个键“sh_list”和一个字符串作为值
这个字符串是问题所在,创建它的代码可能有问题或不打算返回数据,可以将其解析为 json 字符串。
首先是字符串
"\"[{'position': 1, 'item': 'Display'},
{'position': 3, 'item': 'Keyboard'},
{'position': 4, 'item': 'Headphones'}]\"
包含一个前导和一个尾随双引号。但即使你去掉这些,内容也会包含单引号而不是双引号。Json 需要双引号。
所以你可以用
fixed_json = sh_list[1:-1].replace("'", '"')
aslist = json.load(fixed_json)
print(repr(aslist[0])
但这绝对不是健壮的代码。如果可能的话,我建议从源头解决问题并更改生成这些“有趣”字符串的代码
推荐阅读
- python - PuLP 挂在不可行的整数 LP 问题上
- php - 我的一些输入字段没有发布到 php
- ruby-on-rails - 没有找到 LeadsController#create 的模板,渲染头:no_content
- html - 使用 HTML + 辅助功能,是否有显示“此内容的音频可用”的标准?
- css - 边缘问题:CSS 网格单元格中的高度 100% 获得 100% 宽度的值
- jmeter - 在 JMeter 中,如何从 REST POST 请求(而不是响应)中捕获值?
- node.js - 在 NodeJS 中访问 AWS SSM 参数
- javascript - 使用背景图像显示存储为数据 URI 的 SVG:为什么属性值无效?
- php - PHP 套接字在几分钟后过期
- .net - 对于 IBM.WMQ .Net 参考,为什么我的代码没有加载应用程序特定版本的 amqmdnet.dll?