Python json


Python's json module provides an easy way to encode and decode data in JSON (JavaScript Object Notation) format.

JSON is a popular data interchange format that is lightweight, easy for humans to read and write, and easy for machines to parse and generate.


Importing the json module

import json


JSON Serialization

Converting Python objects to JSON strings

import json

# A Python dictionary
data = {
    "name": "John",
    "age": 30,
    "city": "New York"
}

# Convert Python dictionary to JSON string
json_string = json.dumps(data)
print(json_string)  # Output: {"name": "John", "age": 30, "city": "New York"}


JSON Deserialization

Converting JSON strings to Python objects

import json

# A JSON string
json_string = '{"name": "John", "age": 30, "city": "New York"}'

# Convert JSON string to Python dictionary
data = json.loads(json_string)
print(data)  # Output: {'name': 'John', 'age': 30, 'city': 'New York'}


JSON Pretty Printing

prints a JSON string in a readable format with indentation.

import json

# A JSON string
data = '{"name": "John", "age": 30, "city": "New York"}'

json_string = json.dumps(data, indent=4)
print(json_string)


JSON Sorting Keys

To serialize with sorting keys, default is ASC ( asending) -

import json

# A JSON string
data = '{"name": "John", "age": 30, "city": "New York"}'
json_string = json.dumps(data, sort_keys=True)
print(json_string)  # Output: {"age": 30, "city": "New York", "name": "John"}


Create JSON with Custom Serialization

If you have a custom object, you need to provide a custom serialization method. 

import json
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

def person_to_dict(obj):
    if isinstance(obj, Person):
        return {"name": obj.name, "age": obj.age}
    raise TypeError("Object of type Person is not JSON serializable")

person = Person("John", 30)
json_string = json.dumps(person, default=person_to_dict)
print(json_string)  # Output: {"name": "John", "age": 30}


This examples covers the basic usage of the json module for both serialization and deserialization of data in JSON format