SwadhyAI Notes

All Python notes

Python JSON 📄

JSON Processing

JSON (JavaScript Object Notation) is a lightweight data-interchange format. Python has a built-in package called json to work with JSON data.

🗣️ Analogy: The Universal Translator

Think of JSON as a Universal Translator or a common language (like English in international business).
- Your Python program speaks "Python Dictionary".
- A JavaScript website speaks "JavaScript Object".
- To talk to each other, they both convert their data to JSON (text) to send it across the internet.

📥 Parsing JSON (Read)

Use json.loads() to parse a JSON string into a Python dictionary.

python
import json

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

# Parse
data = json.loads(json_str)

print(data["age"]) # 30

📤 Generating JSON (Write)

Use json.dumps() to convert a Python object into a JSON string.

python
import json

data = {
  "name": "John",
  "age": 30,
  "city": "New York"
}

json_str = json.dumps(data)
print(json_str)

🎯 Real-World Application: APIs

Almost all modern web APIs return data in JSON format.

python
import json

# Simulating an API response
response = '{"status": "success", "data": {"id": 101, "price": 99.99}}'

parsed = json.loads(response)
print(f"Price: ${parsed['data']['price']}")

🎨 Pretty Printing

You can format the JSON output to be more readable using indent and sort_keys.

python
print(json.dumps(data, indent=4, sort_keys=True))
# Output:
# {
#     "age": 30,
#     "city": "New York",
#     "name": "John"
# }

💡 File Handling

To read/write directly from/to files, use json.load() and json.dump() (without the 's').

python
# Writing to a file
with open('data.json', 'w') as f:
    json.dump(data, f)

# Reading from a file
with open('data.json', 'r') as f:
    data = json.load(f)