如何JSON序列化Python字典?

时间:2022-12-14 00:06:30

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

我正在尝试为JSON序列化创建一个Django函数,并在HttpResponse对象中返回它。

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

I'm using it like this:

我是这样使用的:

return json_response({ howdy : True })

But I get this error:

但是我得到了这个错误:

"bool" object has no attribute "_meta"

Any ideas?

什么好主意吗?

EDIT: Here is the traceback:

编辑:这里是回溯:

http://dpaste.com/38786/

http://dpaste.com/38786/

5 个解决方案

#1


61  

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

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


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.

Django序列化器模块用于序列化Django ORM对象。如果您想要对常规的Python字典进行编码,您应该使用simplejson,它附带Django,以防您还没有安装它。

import json

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

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

我建议用应用程序/javascript内容类型的头(您也可以使用application/json,但这将阻止您在浏览器中调试):

import json

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

#2


30  

What about a JsonResponse Class that extends HttpResponse:

那么扩展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')

#3


5  

With newer versions of Django you can just use JsonResponse provided by django.http:

对于较新的Django版本,您可以使用django.com .http:

from django.http import JsonResponse

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

You can find more details in the official docs.

你可以在官方文档中找到更多的细节。

#4


4  

In python 2.6 and higher there is a nice JSON library, which has many functions among which is json.dumps() which serializes an object into a string.

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

So you can do something like this:

你可以这样做:

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

#5


0  

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

#1


61  

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

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


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.

Django序列化器模块用于序列化Django ORM对象。如果您想要对常规的Python字典进行编码,您应该使用simplejson,它附带Django,以防您还没有安装它。

import json

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

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

我建议用应用程序/javascript内容类型的头(您也可以使用application/json,但这将阻止您在浏览器中调试):

import json

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

#2


30  

What about a JsonResponse Class that extends HttpResponse:

那么扩展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')

#3


5  

With newer versions of Django you can just use JsonResponse provided by django.http:

对于较新的Django版本,您可以使用django.com .http:

from django.http import JsonResponse

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

You can find more details in the official docs.

你可以在官方文档中找到更多的细节。

#4


4  

In python 2.6 and higher there is a nice JSON library, which has many functions among which is json.dumps() which serializes an object into a string.

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

So you can do something like this:

你可以这样做:

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

#5


0  

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