Python Json

1. What is JSON

JSON (JavaScript Object Notation) is a lightweight data-interchange format used for storing and exchanging structured data.

{
  "name": "Alice",
  "age": 30,
  "active": true
}

In Python, JSON is handled using the built-in json module.


2. Importing the JSON Module

import json

Provides methods to convert between Python objects and JSON format.


3. Convert Python Object → JSON String (json.dumps)

import json

data = {"name": "Alice", "age": 30, "city": "Toronto"}
json_string = json.dumps(data)

print(json_string)

Serializes Python objects into a JSON-formatted string.


4. Convert JSON String → Python Object (json.loads)

Deserializes JSON string into Python data structures.


5. Writing JSON to a File (json.dump)

Stores structured data persistently.


6. Reading JSON from a File (json.load)

Loads JSON data into Python objects.


7. Pretty Printing JSON

Improves readability for logs and debugging.


8. Handling Complex Data Types

Non-serializable objects must be converted manually.


9. Sorting JSON Keys

Useful for consistent API responses and hashing.


10. Enterprise Example: API Response Handling

Standard pattern for microservices and REST APIs.


JSON ↔ Python Data Type Mapping

JSON Type
Python Type

Object

dict

Array

list

String

str

Number (int)

int

Number (float)

float

true/false

True/False

null

None


Common JSON Errors

Error
Cause

JSONDecodeError

Invalid JSON syntax

TypeError

Non-serializable object

UnicodeDecodeError

Encoding mismatch


Best Practices

  • Always validate JSON structure

  • Use try-except for decoding

  • Avoid storing sensitive data in plain JSON

  • Format JSON for logs but compress for production

  • Use schema validation (e.g., Pydantic, Marshmallow)


Enterprise Applications

JSON is fundamental in:

  • REST API communication

  • Configuration files

  • Microservices messaging

  • Data interchange between systems

  • AI model metadata storage


Last updated