Get The Most Affordable Hosting in the World!

Starting at just $1.87/month, Vercaa offers unbeatable pricing for world-class web hosting services.

Fast, reliable, and secure hosting to power your website without breaking the bank. Plus, enjoy a free CDN for faster loading times worldwide!

Get Started Now!

JSON stands for JavaScript Object Notation. It is a lightweight data interchange format. It is similar to pickle. However, pickle serialization is Python specific whereas JSON format is implemented by many languages. The json module in Python's standard library implements object serialization functionality that is similar to pickle and marshal modules.

Just as in pickle module, the json module also provides dumps() and loads() function for serialization of Python object into JSON encoded string, and dump() and load() functions write and read serialized Python objects to/from file.

  • dumps() − This function converts the object into JSON format.

  • loads() − This function converts a JSON string back to Python object.

The following example the demonstrates basic usage of these functions −

Example 1

 
import json data=['Rakesh',{'marks':(50,60,70)}] s=json.dumps(data) print (s, type(s)) data = json.loads(s) print (data, type(data))

It will produce the following output −

["Rakesh", {"marks": [50, 60, 70]}] <class 'str'>
['Rakesh', {'marks': [50, 60, 70]}] <class 'list'>

The dumps() function can take optional sort_keys argument. By default it is False. If set to True, the dictionary keys appear in sorted order in the JSON string.

data=['Rakesh',{'marks':(50,60,70)}] s=json.dumps(data, sort_keys=True)

Example 2

The dumps() function has another optional parameter called indent which takes a number as value. It decides length of each segment of formatted representation of json string, similar to pprint output.

 
import json data=['Rakesh',{'marks':(50,60,70)}] s=json.dumps(data, indent = 2) print (s)

It will produce the following output −

[
  "Rakesh",
  {
    "marks": [
      50,
      60,
      70
    ]
  }
]

The json module also has object-oriented API corresponding to above functions. There are two classes defined in the module − JSONEncoder and JSONDecoder.

JSONEncoder Class

Object of this class is encoder for Python data structures. Each Python data type is converted in corresponding JSON type as shown in following table −

Python JSON
Dict object
list, tuple array
Str string
int, float, int- & float-derived Enums number
True true
False false
None null

The JSONEncoder class is instantiated by JSONEncoder() constructor. Following important methods are defined in encoder class −

  • encode() − serializes Python object into JSON format.

  • iterencode() − Encodes the object and returns an iterator yielding encoded form of each item in the object.

  • indent − Determines indent level of encoded string.

  • sort_keys − is either true or false to make keys appear in sorted order or not.

  • check_circular − if True, check for circular reference in container type object.

The following example encodes Python list object.

Example

import json data=['Rakesh',{'marks':(50,60,70)}] e=json.JSONEncoder()

Using iterencode() method, each part of the encoded string is displayed as below −

 
import json data=['Rakesh',{'marks':(50,60,70)}] e=json.JSONEncoder() for obj in e.iterencode(data): print (obj)

It will produce the following output −

["Rakesh"
, 
{
"marks"
: 
[50
, 60
, 70
]
}
]

JSONDEcoder class

Object of this class helps in decoded in json string back to Python data structure. Main method in this class is decode(). Following example code retrieves Python list object from encoded string in earlier step.

Example

 
import json data=['Rakesh',{'marks':(50,60,70)}] e=json.JSONEncoder() s = e.encode(data) d=json.JSONDecoder() obj = d.decode(s) print (obj, type(obj))

It will produce the following output −

['Rakesh', {'marks': [50, 60, 70]}] <class 'list'>

JSON with Files/Streams

The json module defines load() and dump() functions to write JSON data to a file like object − which may be a disk file or a byte stream and read data back from them.

dump() Function

This function encodes Python object data in JSON format and writes it to a file. The file must be having write permission.

Example

import json data=['Rakesh', {'marks': (50, 60, 70)}] fp=open('json.txt','w') json.dump(data,fp) fp.close()

This code will create 'json.txt' in current directory. It shows the contents as follows −

["Rakesh", {"marks": [50, 60, 70]}]

load() Function

This function loads JSON data from the file and constructs Python object from it. The file must be opened with read permission.

Example

import json fp=open('json.txt','r') ret=json.load(fp) print (ret)
 
 
 
 
The End! should you have any inquiries, we encourage you to reach out to the Vercaa Support Center without hesitation.
Bu cavab sizə kömək etdi? 1 istifadəçi bunu faydalı hesab edir (1 səs)