【问题标题】:How do I JSON serialize a Python dictionary?如何 JSON 序列化 Python 字典?
【发布时间】:2010-10-22 08:06:14
【问题描述】:

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

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/

【问题讨论】:

  • 没有实际的回溯,没有。

标签: django json serialization


【解决方案1】:

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


Django 序列化程序模块旨在序列化 Django ORM 对象。如果你想编码一个普通的 Python 字典,你应该使用 simplejson,它是 Django 附带的,以防你还没有安装它。

import json

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

我建议将它与 application/javascript Content-Type 标头一起发送回来(您也可以使用 application/json 但这会阻止您在浏览器中进行调试):

import json

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

【讨论】:

【解决方案2】:

扩展 HttpResponse 的 JsonResponse Class 怎么样:

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

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

    所以你可以这样做:

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

    【讨论】:

      【解决方案4】:
      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
      

      【讨论】:

        【解决方案5】:

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

        from django.http import JsonResponse
        
        def my_view(request):
            json_object = {'howdy': True}
            return JsonResponse(json_object)
        

        您可以在official docs找到更多详细信息。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2017-05-17
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多