【问题标题】:How can I quickly dump a query result set into JSON?如何快速将查询结果集转储为 JSON?
【发布时间】:2011-06-07 14:46:54
【问题描述】:
import simplejson as json
results = Content.objects.filter(blah)
theresult_json = json.dumps(results)

这不行!!

【问题讨论】:

    标签: javascript python django json


    【解决方案1】:

    http://docs.djangoproject.com/en/dev/topics/serialization/怎么样

    ?

    from django.core import serializers
    data = serializers.serialize('json', SomeModel.objects.all())
    
    # it's pretty useful and quick.
    data = serializers.serialize('json', SomeModel.objects.all(), fields=('foo','bar'))
    

    【讨论】:

      【解决方案2】:

      results 是一个 Python 对象。 simplejson.dumps 仅适用于 python dict's/list's。

      您需要先将结果对象转换为字典。您可以像这样手动操作:

      l = [] 
      
      for result in results:
          d = {
              'attr1': result.attr1,
              'attr2': result.attr2,
              ...
          }
          l.append(d)
      
      theresult_json = simplejson.dumps(l)
      

      或动态地使用对象__dict__ 方法,之后从中删除非 JSON 可序列化属性:

      l = [] 
      
      for result in results:
          d = result.__dict__
          # remove attributes from dict which are not JSON-serializable with del d[key]
          l.append(d)
      
      theresult_json = simplejson.dumps(l)
      

      【讨论】:

        【解决方案3】:

        根据您要执行的操作,您可能还想查看Piston。它具有特殊的 Emitter 类,用于将您的对象转储为 JSON 格式、XML 格式等......如果您正在构建 AJAX 或 API 端点,活塞框架非常有用。

        【讨论】:

          猜你喜欢
          • 2019-05-28
          • 1970-01-01
          • 2011-06-26
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-12-23
          相关资源
          最近更新 更多