[Fixed]-DJango: formatting json serialization

31👍

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

7👍

Python (unrelated to Django and starting with 2.6) has a built in json library that can accomplish the indentation you require. 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. 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. 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.

As for sorting your output, you can just use the order_by method on your query set:

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. It may help you in the long run as it provides many other convenient features that help towards that end.

2👍

With Django 1.7 I can get nicely indented JSON by using the indent parameter of the serializer. 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. 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. For instance, I use itertools.chain to order different querysets that return instances of different models.

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.

👤Louis

-3👍

JSON doesn’t have indentation, it’s simply structured data. Browsers or other tools may format the JSON so that it looks nice but by default it’s not there. It’s also not part of the JSON as the formatting is just how it looks on the screen. JSON is often processed by other code or services so they don’t care about indentation, as long as the data is structured correctly.

Leave a comment