Python JSON

JSON is the short form for JavaScript Object Notation.This is a lightweight data-interchange format that is relatively easy to read and write for humans but easier for machines to parse. It is the language based from which JSON may be built; however, it is not language dependent, and now can work with several programming languages, most notably with Python.

In Python, the json module provides a way to encode and decode JSON data. Let’s dive into the details:

What is JSON?

JSON represents data as key-value pairs, arrays, and nested structures. It is most commonly used to transfer data between a server and a client in web applications.

JSON Syntax

  • Objects: Represented as key-value pairs enclosed in {}.
{
  "name": "John",
  "age": 30,
  "isStudent": false
}
  • Arrays: Represented as a list of values enclosed in [].
["apple", "banana", "cherry"]
  • Values: Can be strings, numbers, booleans, null, objects, or arrays.

Python json Module

The json module provides two major functionalities:

  1. Serialization: It converts Python objects into JSON strings.
  2. Deserialization: It converts JSON strings into Python objects.

1. Serialization (Python → JSON)

Serialization is done using the json.dump() and json.dumps() methods.

json.dumps()

Converts a Python object into a JSON string.

import json

data = {
    "name": "Alice",
    "age": 25,
    "isStudent": True
}

json_string = json.dumps(data)
print(json_string)  # {"name": "Alice", "age": 25, "isStudent": true}

json.dump()

Writes a Python object as JSON into a file.

with open("data.json", "w") as file:
    json.dump(data, file)

2. Deserialization (JSON → Python)

Deserialization is done using the json.load() and json.loads() methods.

json.loads()

Converts a JSON string into a Python object.

json_data = '{"name": "Bob", "age": 30, "isStudent": false}'
python_data = json.loads(json_data)
print(python_data) # {'name': 'Bob', 'age': 30, 'isStudent': False}

json.load()

Reads JSON data from a file and converts it into a Python object.

with open("data.json", "r") as file:
    data = json.load(file)
    print(data)

Supported Conversions

JSON TypePython Type
Objectdict
Arraylist
Stringstr
Number (int)int
Number (float)float
trueTrue
falseFalse
nullNone

Customizing Serialization

You can customize the behavior of json.dumps() with optional parameters like indent, sort_keys, and separators.

Pretty Printing

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

Sorting Keys

json_string = json.dumps(data, sort_keys=True)
print(json_string)

Handling Errors

  • JSONDecodeError: Raised if the JSON string is invalid.
  • Example:
try:
    json_data = json.loads('{"name": "Alice" "age": 25}')  # Missing comma
except json.JSONDecodeError as e:
    print("Invalid JSON:", e)

Use Cases

  1. Web APIs: JSON is widely used in REST APIs to exchange data.
  2. Configuration Files: Applications often use JSON files for settings.
  3. Data Storage: JSON is used for lightweight, human-readable storage.