JSONField in serializers - Django REST Framework - GeeksforGeeks

22 Mar, 2022
In Django REST Framework the very concept of Serializing is to convert DB data to a datatype that can be used by javascript. Every serializer comes with some fields (entries) which are going to be processed. For example if you have a class with name Employee and its fields as Employee_id, Employee_name, is_admin, etc. Then, you would need AutoField, CharField and BooleanField for storing and manipulating data through Django. Similarly, serializer also works with same principle and has fields that are used to create a serializer. This article revolves around JSONField in Serializers in Django REST Framework.
JSONField is basically a field class that validates that the incoming data structure consists of valid JSON primitives. In its alternate binary mode, it will represent and validate JSON-encoded binary strings. It has the following arguments –
binary – If set to True then the field will output and validate a JSON encoded string, rather than a primitive data structure. Defaults to False.
encoder – Use this JSON encoder to serialize input object. Defaults to None.
Syntax – 
field_name = serializers.JSONField(*args, **kwargs)
To explain the usage of JSONField, let’s use the same project setup from – How to Create a basic API using Django Rest Framework ?. Now that you have a file called serializers in your project, let’s create a serializer with JSONField as the field. 
Python3
# import serializer from rest_frameworkfrom rest_framework import serializers class Geeks(object):    def __init__(self, json_data):        self.json_data = json_data # create a serializerclass GeeksSerializer(serializers.Serializer):    # initialize fields    json_data = serializers.JSONField()    
Now let us create some objects and try serializing them and check if they are actually working, Run, –
Python manage.py shell
Now, run following python commands in the shell
# create a json object
>>> import json
>>> x = json.dumps({"name":"Naveen", "Age":"21"})
>>> x
'{"name": "Naveen", "Age": "21"}'

# import everything from serializers
>>> from apis.serializers import *

# create a object of type Geeks
>>> obj = Geeks(x)

# serialize the object
>>> serializer = GeeksSerializer(obj)

# print serialized data
>>> serializer.data
{'json_data': '{"name": "Naveen", "Age": "21"}'}
Here is the output of all these operations on terminal – 
Note that prime motto of these fields is to impart validations, such as JSONField validates the data to JSON only. Let’s check if these validations are working or not –
# Create a dictionary and add invalid values
>>> data = {}
>>> data['json_data'] = x

# dictionary created
>>> data
{'json_data': '{"name": "Naveen", "Age": "21"}'}

# deserialize the data
>>> serializer = GeeksSerializer(data=data)

# check if data is valid
>>> serializer.is_valid()
True

# check the errors
>>> serializer.errors
{}
Here is the output of these commands which clearly shows json_data valid – 
Validations are part of Deserialization and not serialization. As explained earlier, serializing is process of converting already made data into another data type, so there is no requirement of these default validations out there. Deserialization requires validations as data needs to be saved to database or any more operation as specified. So if you serialize data using these fields that would work.
.math-table { border-collapse: collapse; width: 100%; } .math-table td { border: 1px solid #5fb962; text-align: left !important; padding: 8px; } .math-table th { border: 1px solid #5fb962; padding: 8px; } .math-table tr>th{ background-color: #c6ebd9; vertical-align: middle; } .math-table tr:nth-child(odd) { background-color: #ffffff; } 
sagartomar9927
Django-REST
Python Django
rest-framework
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists