JSON is written as key and value pair. JSON is very similar to Python dictionary. Python supports JSON, and it has an inbuilt library as a JSON.

JSON Library in Python

‘marshal‘ and ‘pickle’ external modules of Python maintain a version of JSON Python library. Working with JSON in Python to perform JSON related operations like encoding and decoding, you need to first import JSON library and for that in your .py file, Following methods are available in the JSON Python module

Python to JSON (Encoding)

JSON Library of Python performs following translation of Python objects into JSON objects by default Converting Python data to JSON is called an Encoding operation. Encoding is done with the help of JSON library method – dumps() Now lets perform our first json.dumps encoding example with Python: Output: Let’s see an example of Python write JSON to file for creating a JSON file of the dictionary using the same function dump() Output: Nothing to show…In your system json_file.json is created. You can check that file as shown in the below write JSON to file Python example.

JSON to Python (Decoding)

JSON string decoding is done with the help of inbuilt method json.loads() & json.load() of JSON library in Python. Here translation table show example of JSON objects to Python objects which are helpful to perform decoding in Python of JSON string. Let’s see a basic parse JSON Python example of decoding with the help of json.loads function, Output:

Decoding JSON File or Parsing JSON file in Python

Now, we will learn how to read JSON file in Python with Python parse JSON example: NOTE: Decoding JSON file is File Input /Output (I/O) related operation. The JSON file must exist on your system at specified the location that you mention in your program. Python read JSON file Example: Here data is a dictionary object of Python as shown in the above read JSON file Python example. Output:

Compact Encoding in Python

When you need to reduce the size of your JSON file, you can use compact encoding in Python. Example, Output:

Format JSON code (Pretty print)

The aim is to write well-formatted code for human understanding. With the help of pretty printing, anyone can easily understand the code.

Example: Output:

To better understand this, change indent to 40 and observe the output-

Ordering the JSON code: sort_keys attribute in Python dumps function’s argument will sort the key in JSON in ascending order. The sort_keys argument is a Boolean attribute. When it’s true sorting is allowed otherwise not. Let’s understand with Python string to JSON sorting example. Example, Output: As you may observe the keys age, cars, children, etc are arranged in ascending order.

Complex Object encoding of Python

A Complex object has two different parts that is

Real part Imaginary part

Example: 3 +2i Before performing encoding of a complex object, you need to check a variable is complex or not. You need to create a function which checks the value stored in a variable by using an instance method. Let’s create the specific function for check object is complex or eligible for encoding. Output:

Complex JSON object decoding in Python

To decode complex object in JSON, use an object_hook parameter which checks JSON string contains the complex object or not. Lets understand with string to JSON Python Example, Output:

Overview of JSON Serialization class JSONEncoder

JSONEncoder class is used for serialization of any Python object while performing encoding. It contains three different methods of encoding which are

default(o) – Implemented in the subclass and return serialize object for o object. encode(o) – Same as JSON dumps Python method return JSON string of Python data structure. iterencode(o) – Represent string one by one and encode object o.

With the help of encode() method of JSONEncoder class, we can also encode any Python object as shown in the below Python JSON encoder example. Output:

Overview of JSON Deserialization class JSONDecoder

JSONDecoder class is used for deserialization of any Python object while performing decoding. It contains three different methods of decoding which are

default(o) – Implemented in the subclass and return deserialized object o object. decode(o) – Same as json.loads() method return Python data structure of JSON string or data. raw_decode(o) – Represent Python dictionary one by one and decode object o.

With the help of decode() method of JSONDecoder class, we can also decode JSON string as shown in below Python JSON decoder example. Output:

Decoding JSON data from URL: Real Life Example

We will fetch data of CityBike NYC (Bike Sharing System) from specified URL(https://feeds.citibikenyc.com/stations/stations.json) and convert into dictionary format. Python load JSON from file Example: NOTE:- Make sure requests library is already installed in your Python, If not then open Terminal or CMD and type

(For Python 3 or above) pip3 install requests

Output:

Class json.JSONDecoderError handles the exception related to decoding operation. and it’s a subclass of ValueError. Exception – json.JSONDecoderError(msg, doc) Parameters of Exception are,

msg – Unformatted Error message doc – JSON docs parsed pos – start index of doc when it’s failed lineno – line no shows correspond to pos colon – column no correspond to pos

Python load JSON from file Example:

Infinite and NaN Numbers in Python

JSON Data Interchange Format (RFC – Request For Comments) doesn’t allow Infinite or Nan Value but there is no restriction in Python- JSON Library to perform Infinite and Nan Value related operation. If JSON gets INFINITE and Nan datatype than it’s converted it into literal. Example, Output:

Repeated key in JSON String

RFC specifies the key name should be unique in a JSON object, but it’s not mandatory. Python JSON library does not raise an exception of repeated objects in JSON. It ignores all repeated key-value pair and considers only last key-value pair among them.

Example,

Output:

CLI (Command Line Interface) with JSON in Python

json.tool provides the command line interface to validate JSON pretty-print syntax. Let’s see an example of CLI

Output:

Advantages of JSON in Python

Easy to move back between container and value (JSON to Python and Python to JSON) Human readable (Pretty-print) JSON Object Widely used in data handling. Doesn’t have the same data structure in the single file.

Implementation Limitations of JSON in Python

In deserializer of JSON range and prediction of a number The Maximum length of JSON string and arrays of JSON and nesting levels of object.

Python JSON Cheat Sheet