Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DJango: formatting json serialization

I have the following DJango view

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": "[email protected]"}}, {"pk": 4, "model": "test.company", "fields": {"companylogo": null, "phonenumber": "641-7778889", "name": "remixa", "email": "[email protected]"}}, {"pk": 2, "model": "test.company", "fields": {"companylogo": null, "phonenumber": "658-2233444", "name": "remix", "email": "[email protected]"}}, {"pk": 7, "model": "test.company", "fields": {"companylogo": null, "phonenumber": "996-7778880", "name": "remix", "email": "[email protected]"}}]

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 i.e. instead of one long line to see something like this:

[
  {
     "pk": 1, 
     "model": "test.company", 
     "fields": 
     {
         "companylogo": null, 
         "phonenumber": "741.999.5554", 
         "name": "Remax", 
         "email": "[email protected]"
     }
  }, 
  {
     "pk": 4, 
     "model": "test.company", 
     "fields": 
     {
        "companylogo": null,  
        "phonenumber": "641-7778889", 
        "name": "remixa", 
        "email": "[email protected]"
     }
  }, 
  ....
 }

]

like image 471
liv a Avatar asked Nov 21 '13 00:11

liv a


1 Answers

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

like image 155
Hohenheim Avatar answered Oct 03 '22 08:10

Hohenheim