解决图片对象不能json序列化问题:<ImageFieldFile: image/background_IXSZChD.jpg> is not JSON serializable

json.dumps(img_list,)不可以序列化图片,不知道怎么回事(py3)报错:

Traceback (most recent call last):
  File "/home/python35/lib/python3.5/site-packages/django/core/handlers/exception.py", line 41, in inner
    response = get_response(request)
  File "/home/python35/lib/python3.5/site-packages/django/core/handlers/base.py", line 187, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/home/python35/lib/python3.5/site-packages/django/core/handlers/base.py", line 185, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/home/q10/myProject/userManage/tempManage.py", line 55, in useImg
    return HttpResponse(json.dumps(img_list,sort_keys=True),content_type="application/json")
  File "/home/python35/lib/python3.5/json/__init__.py", line 237, in dumps
    **kw).encode(obj)
  File "/home/python35/lib/python3.5/json/encoder.py", line 198, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File "/home/python35/lib/python3.5/json/encoder.py", line 256, in iterencode
    return _iterencode(o, 0)
  File "/home/python35/lib/python3.5/json/encoder.py", line 179, in default
    raise TypeError(repr(o) + " is not JSON serializable")
TypeError: <ImageFieldFile: image/background_IXSZChD.jpg> is not JSON serializable
[15/Nov/2017 16:08:18] "POST /useImg/ HTTP/1.1" 500 14696
Performing system checks...


原代码:

img_list.append({"id":i.id,"img":i.img,"name":i.img_name,"user":i.img_user.user_nickname})
        return HttpResponse(json.dumps(img_list,sort_keys=True),content_type="application/json")


查了下是img对象没有被json序列化,要str(img对象)才可以,:


修正后:


img_list.append({"id":i.id,"img":str(i.img),"name":i.img_name,"user":i.img_user.user_nickname})
        return HttpResponse(json.dumps(img_list,sort_keys=True),content_type="application/json")

区别在于
"img":str(i.img)

,加了str()转换 就ok了,

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值