27

I'm trying to figure out a way to serialize some Django model object to JSON format, something like:

j = Job.objects.get(pk=1)
##############################################
#a way to get the JSON for that j variable???
##############################################

I don't want:

from django.core import serializers
serializers.serialize('json', Job.objects.get(pk=1),ensure_ascii=False)

Because it returns JSON array, not a single object representation.

Any ideas?

One way I'm thinking of: is to find a way to get a hash(attribute,value) of the object and then use simplejson to get the JSON representation of it, however I don't know how to get that hash.

khelll
  • 23,590
  • 15
  • 91
  • 109
  • Possible duplicate of [How do you serialize a model instance in Django?](https://stackoverflow.com/questions/757022/how-do-you-serialize-a-model-instance-in-django) – kagronick May 29 '19 at 14:17

3 Answers3

34

How about just massaging what you get back from serializers.serialize? It is not that hard to trim off the square brackets from the front and back of the result.

job = Job.objects.get(pk=1)
array_result = serializers.serialize('json', [job], ensure_ascii=False)
just_object_result = array_result[1:-1]

Not a fancy answer but it will give you just the object in json notation.

istruble
  • 13,363
  • 2
  • 47
  • 52
  • Isn't the the same as putting [0] at the end of the array_result? just_object_result = array_result[0] – timj98 Apr 24 '18 at 19:14
  • 2
    No. `array_result` is an array serialized into json and will be a string bookended by `[]`'s at the start and end. If `array_result = '[...]'` then `arrary_result[1:-1]` gives `'...'` and `array_result[0]` gives `'['`. This question was all about serializing data into a string. The`s[start:end]` notation is a [slice of string s](https://docs.python.org/3/library/stdtypes.html#common-sequence-operations). – istruble Apr 24 '18 at 21:52
  • 3
    This should be inbuilt inside a Model, like a `.to_json()` method. – Dev Aggarwal Jun 06 '18 at 20:57
20

Method-1

Use Django Serializer with python format

from django.core import serializers

j = Job.objects.get(pk=1)
response = serializers.serialize('python', [j], ensure_ascii=False)

Method-2

use json format while serializing and loads the string response

import json
from django.core import serializers

j = Job.objects.get(pk=1)
json_str_response = serializers.serialize('json', [j], ensure_ascii=False)
response = json.loads(json_str_response)[0]

Method-3

Use Django REST Framework's Serializer class define a serializer class and serialize the instance as

from rest_framework import serializers


class JobSerializer(serializers.ModelSerializer):
    class Meta:
        model = Job
        fields = '__all__'


j = Job.objects.get(pk=1)
response = JobSerializer(instance=j).data

Reference
1. Serializer Django model object

Ehsan88
  • 3,569
  • 5
  • 29
  • 52
JPG
  • 82,442
  • 19
  • 127
  • 206
  • 1
    Holy shit, thank you for Method 3. So many crazy answers out there to this and i just needed to set instance to the return object and then reference the data on it. THANK YOU. – AlxVallejo Jul 22 '20 at 14:15
  • 1
    sadly I get only the name of fields when trying to return the response from your Method 3 in an HttpResponse from view – tikej Mar 31 '21 at 13:39
15

I would suggest using Django's model_to_dict. If I'm not mistaken, serializers.serialize() relies on it, too, but it only works for list, not single model instance. That's how you get a dict instance with your model fields out of a single model:

from django.forms.models import model_to_dict

# assuming obj is your model instance
dict_obj = model_to_dict( obj )

You now just need one straight json.dumps call:

import json
json.dumps(dict_obj)
Pavel Daynyak
  • 1,714
  • 1
  • 11
  • 7