我如何JSON序列化Python字典?

时间:2009-04-28 14:01:14

标签: django json serialization

我正在尝试为JSON编写一个Django函数来序列化某些内容并将其返回到HttpResponse对象中。

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/

5 个答案:

答案 0 :(得分:64)

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


Django序列化程序模块用于序列化Django ORM对象。如果你想编码一个普通的Python字典,你应该使用simplejson,它与Django一起提供,以防你没有安装它。

import json

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

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

import json

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

答案 1 :(得分:31)

扩展 HttpResponse JsonResponse 怎么样:

from django.http import HttpResponse
from django.utils import simplejson

class JsonResponse(HttpResponse):
    def __init__(self, data):
        content = simplejson.dumps(data,
                                   indent=2,
                                   ensure_ascii=False)
        super(JsonResponse, self).__init__(content=content,
                                           mimetype='application/json; charset=utf8')

答案 2 :(得分:8)

使用较新版本的Django,您只需使用django.http提供的JsonResponse:

from django.http import JsonResponse

def my_view(request):
    json_object = {'howdy': True}
    return JsonResponse(json_object)

您可以在official docs

中找到更多详细信息

答案 3 :(得分:5)

在python 2.6及更高版本中有一个很好的JSON library,它有许多函数,其中json.dumps()将一个对象序列化为一个字符串。

所以你可以这样做:

import json
print json.dumps({'howdy' : True })

答案 4 :(得分:1)

import json

my_list = range(1,10) # a list from 1 to 10

with open('theJsonFile.json', 'w') as file_descriptor:

         json.dump(my_list, file_descriptor) #dump not dumps, dumps = dump-string
相关问题