JSON (JavaScript Object Notation) is a lightweight data-interchange format that is easy for humans to read and write and easy for machines to parse and generate. It’s extensively used in web applications for data transmission.

With Python’s built-in json module, encoding and decoding JSON becomes a straightforward task. This means converting Python objects into JSON formatted strings and converting JSON strings back into Python objects.

Encoding Python Objects to JSON (json.dumps)

Let’s delve into a practical example. Imagine you have a Python class called Student, and you’d like to serialize an instance of this class into JSON format.

Below, we instantiate a Student object and then use the json.dumps() method to transform this Python object into a JSON string.

import json

class Student:
def __init__(self, id, name, password):
self.id = id
self.name = name
self.password = password

pythonObj = Student(1,'ashley','123456')

# Serialize Python object to JSON formatted string
jsonObj = json.dumps(pythonObj.__dict__)
print(jsonObj)

As seen above, the result is a JSON-formatted string that represents the Student object:

{"password": "123456", "id": 1, "name": "ashley"}

Decoding JSON to Python Objects (json.loads)

The reverse process, decoding, converts a JSON string into a Python dictionary or object. This is performed using the json.loads() method.

Here’s how you can convert the earlier JSON string into a Python dictionary:

import json

j = json.loads('{"password": "123456", "id": 1, "name": "ashley"}')
print(j["name"])

For a more advanced use-case, you might want to decode the JSON string directly into a Python object. To achieve this, first define the Python class and then instantiate it using the parsed JSON data:

import json

class Student:
def __init__(self, id, name, password):
self.id = id
self.name = name
self.password = password

j = json.loads('{"password": "123456", "id": 1, "name": "ashley"}')
pythonObj = Student(**j)

print(pythonObj.id)
print(pythonObj.name)
print(pythonObj.password)

Understanding JSON encoding and decoding in Python is crucial for any developer working on data transmission or web application tasks. Python’s native support for JSON makes these operations intuitive and efficient.