如何将JSON序列化为Python字典? [英] How do I JSON serialize a Python dictionary?

查看:136
本文介绍了如何将JSON序列化为Python字典?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试制作一个Django函数,用于JSON序列化,并将其返回到一个 HttpResponse 对象中。

I'm trying to make a Django function for JSON serializing something and returning it in an HttpResponse object.

def json_response(something):
    data = serializers.serialize("json", something)
    return HttpResponse(data)

我正在使用它:

return json_response({ howdy : True })

但是我收到这个错误:

"bool" object has no attribute "_meta"

任何想法?

编辑:这是追溯:

http://dpaste.com/38786/

推荐答案

更新:Python现在有自己的json处理程序,只需使用 import json 而不是使用 simplejson

Update: Python now has its own json handler, simply use import json instead of using simplejson.

Django序列化器模块旨在序列化Django ORM对象。如果你想编码一个常规的Python字典,你应该使用simplejson,它随附Django,以防你没有安装它。

The Django serializers module is designed to serialize Django ORM objects. If you want to encode a regular Python dictionary you should use simplejson, which ships with Django in case you don't have it installed already.

import json

def json_response(something):
    return HttpResponse(json.dumps(something))

我建议使用应用程序/ JavaScript Content-Type标头发回(您也可以使用application / json,但这将阻止您在浏览器中进行调试):

I'd suggest sending it back with an application/javascript Content-Type header (you could also use application/json but that will prevent you from debugging in your browser):

import json

def json_response(something):
    return HttpResponse(
        json.dumps(something),
        content_type = 'application/javascript; charset=utf8'
    )

这篇关于如何将JSON序列化为Python字典?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆