简体   繁体   English

DJango:格式化json序列化

[英]DJango: formatting json serialization

I have the following DJango view我有以下 DJango 视图

def company(request):
    company_list = Company.objects.all()
    output = serializers.serialize('json', company_list, fields=('name','phonenumber','email','companylogo'))
    return HttpResponse(output, content_type="application/json")

it result as follows:结果如下:

[{"pk": 1, "model": "test.company", "fields": {"companylogo": null, "phonenumber": "741.999.5554", "name": "Remax", "email": "home@remax.co.il"}}, {"pk": 4, "model": "test.company", "fields": {"companylogo": null, "phonenumber": "641-7778889", "name": "remixa", "email": "a@aa.com"}}, {"pk": 2, "model": "test.company", "fields": {"companylogo": null, "phonenumber": "658-2233444", "name": "remix", "email": "b@bbb.com"}}, {"pk": 7, "model": "test.company", "fields": {"companylogo": null, "phonenumber": "996-7778880", "name": "remix", "email": "a@aba.com"}}]

my questions: 1. can i control the order of the fields 2. can i change the name of the fields 3. I was expecting to see the result with indentation in the browser ie instead of one long line to see something like this:我的问题: 1. 我可以控制字段的顺序 2. 我可以更改字段的名称 3. 我希望在浏览器中看到带有缩进的结果,即,而不是一行很长的行来看到这样的东西:

[
  {
     "pk": 1, 
     "model": "test.company", 
     "fields": 
     {
         "companylogo": null, 
         "phonenumber": "741.999.5554", 
         "name": "Remax", 
         "email": "home@remax.co.il"
     }
  }, 
  {
     "pk": 4, 
     "model": "test.company", 
     "fields": 
     {
        "companylogo": null,  
        "phonenumber": "641-7778889", 
        "name": "remixa", 
        "email": "a@aa.com"
     }
  }, 
  ....
 }

] ]

you can get pretty format in this way:你可以通过这种方式获得漂亮的格式:

return JsonResponse(your_json_dict, json_dumps_params={'indent': 2})

django doc as the first comment say django doc 作为第一条评论说

Python (unrelated to Django and starting with 2.6) has a built in json library that can accomplish the indentation you require. Python(与 Django 无关,从 2.6 开始)有一个内置的json库,可以完成你需要的缩进。 If you are looking for something quick and dirty for debug purposes you could do something like this:如果您正在寻找用于调试目的的快速而肮脏的东西,您可以执行以下操作:

from django.http import HttpResponse
from django.core import serializers
import json


def company(request, pretty=False):
    company_list = Company.objects.all()
    output = serializers.serialize('json', company_list, fields=('name','phonenumber','email','companylogo'))
    if pretty:
        output = json.dumps(json.loads(output), indent=4))
    return HttpResponse(output, content_type="application/json")

But this is a performance issue if the Company model is large.但如果Company模型很大,这是一个性能问题。 I recommend taking Dan R's advice and use a browser plugin to parse and render the json or come up with some other client side solution.我建议采纳 Dan R 的建议并使用浏览器插件来解析和呈现 json 或提出其他一些客户端解决方案。 I have a script that takes in a json file and does exactly the same thing as the code above, reads in the json and prints it out with indent=4 .我有一个脚本,它接收一个 json 文件并执行与上面的代码完全相同的操作,读取 json 并使用indent=4其打印出来。

As for sorting your output, you can just use the order_by method on your query set:至于对输出进行排序,您可以在查询集上使用order_by方法:

def company(request):
    company_list = Company.objects.order_by("sorting_field")
    ...

And if you always want that model sorted that way, you can use the ordering meta-class option:如果您总是希望以这种方式对模型进行排序,则可以使用排序元类选项:

class Company(models.Model):

    class Meta:
        ordering = ["sorting_field"]
    ...

As a final note, If your intent is to expose your models with a web service, I highly recommend taking a look at tastypie .最后要说明的是,如果您的目的是使用 Web 服务公开模型,我强烈建议您查看一下ttletypie It may help you in the long run as it provides many other convenient features that help towards that end.从长远来看,它可能会对您有所帮助,因为它提供了许多其他方便的功能来帮助实现这一目标。

With Django 1.7 I can get nicely indented JSON by using the indent parameter of the serializer.在 Django 1.7 中,我可以通过使用序列化程序的indent参数获得很好的缩进 JSON。 For instance, in a command that dumps data from my database:例如,在从我的数据库转储数据的命令中:

self.stdout.write(serializers.serialize("json",
                                        records,
                                        indent=2))

The indent parameter has been in Django since version 1.5. indent参数从 1.5 版开始就存在于 Django 中。 The output I get looks like this:我得到的输出如下所示:

[
{ 
  "fields": {
    "type": "something",
    "word": "something else",
  },
  "model": "whatever",
  "pk": 887060
},
{ 
  "fields": {
    "type": "something more",
    "word": "and another thing",
  },
  "model": "whatever",
  "pk": 887061
},
...

To order your records then you'd have to do what Kevin suggested and use order_by , or whatever method you want to order the records you pass to the serializer.要对您的记录进行排序,那么您必须按照Kevin 的建议进行操作并使用order_by或任何您想要对传递给序列化程序的记录进行排序的方法。 For instance, I use itertools.chain to order different querysets that return instances of different models.例如,我使用itertools.chain对返回不同模型实例的不同查询集进行排序。

The serializer does not support ordering fields according to your preferences, or renaming them.序列化程序不支持根据您的喜好对字段进行排序或重命名。 You have to write your own code to do this or use an external tool.您必须编写自己的代码来执行此操作或使用外部工具。

JSON doesn't have indentation, it's simply structured data. JSON 没有缩进,它只是结构化数据。 Browsers or other tools may format the JSON so that it looks nice but by default it's not there.浏览器或其他工具可能会格式化 JSON,使其看起来不错,但默认情况下它不存在。 It's also not part of the JSON as the formatting is just how it looks on the screen.它也不是 JSON 的一部分,因为格式只是它在屏幕上的外观。 JSON is often processed by other code or services so they don't care about indentation, as long as the data is structured correctly. JSON 通常由其他代码或服务处理,因此它们不关心缩进,只要数据结构正确即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM