TypeError: Object of type 'bytes' is not JSON serializable

def ans_result(request):
   if request.method == "POST":
       redisKey = request.POST.get('ans_uuid')
       msg = DsRedis.OpsAnsibleModel.rpop(redisKey)
       if msg:
           print('---',msg)
           return JsonResponse({'msg': msg, "code": 200, 'data': []})
       else:
           return JsonResponse({'msg': None, "code": 200, 'data': []})

返回是报错如下

TypeError: Object of type 'bytes' is not JSON serializable

查看message的值

 msg = DsRedis.OpsAnsibleModel.rpop(redisKey)
 
 msg取出的值变成了: b'[Done] Ansible Done.'
注: 带有 b 开头的字节

redis中key的值

6) "[Start] Ansible Model: ping  ARGS:"
127.0.0.1:6379[3]> LRANGE  8b3e134d-6ad7-4e21-b5d6-c7dfc1f101a8 0 -1
1) "[Done] Ansible Done."
2) "10.39.6.150 | SUCCESS >> {\n    \"ping\": \"pong\",\n    \"_ansible_parsed\": true,\n    \"_ansible_no_log\": false\n}"
3) "[Start] Ansible Model: ping  ARGS:"
4) "[Done] Ansible Done."
5) "10.39.6.150 | SUCCESS >> {\n    \"ping\": \"pong\",\n    \"_ansible_parsed\": true,\n    \"_ansible_no_log\": false\n}"
6) "[Start] Ansible Model: ping  ARGS:"

解决:

json模块不支持bytes类型,要先将bytes转换为str格式

即: 返回字符串加上 decode方法

def ans_result(request):
   if request.method == "POST":
       redisKey = request.POST.get('ans_uuid')
       msg = DsRedis.OpsAnsibleModel.rpop(redisKey)
       if msg:
           return JsonResponse({'msg': msg.decode(), "code": 200, 'data': []})

注: python3 和python2 之间对字符的编码有很大变化 ,这回导致python2 写的代码在python3里写的代码可能会有异常

python2 和python3 字符编码的差别

你可能感兴趣的:(TypeError: Object of type 'bytes' is not JSON serializable)