首页 > 解决方案 > 无法将字节转换为 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'}

如何进行从字节到字典的转换?

标签: pythonpython-3.xdictionarydjango-rest-framework

解决方案


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])

但这绝对不是健壮的代码。如果可能的话,我建议从源头解决问题并更改生成这些“有趣”字符串的代码


推荐阅读