Working with JSON in Python - potatoscript/json GitHub Wiki

🐍 Working with JSON in Python: Unleash the Power of Data! πŸŽ‰

Welcome to the Amazing World of JSON and Python! πŸπŸ’‘
JSON is the go-to format for exchanging data, and Python makes it super easy to handle! πŸ˜ŽπŸ“š


🎯 What is JSON in Python?

  • JSON (JavaScript Object Notation): A lightweight format to store and exchange data.
  • Python + JSON: Python provides the json module to parse, encode, and manipulate JSON effortlessly! πŸš€

πŸ”₯ 1. Importing the json Module

Before working with JSON, import the json module.

import json

πŸ“ 2. Converting JSON to Python (Deserialization/Parsing)

When you receive JSON data from an API or file, it’s in string format. To convert it into a Python object, use:

json.loads()  # Convert JSON string to Python object

🎯 Example: Convert JSON String to Python Dictionary

import json

# JSON string
json_data = '{"name": "Lucy Berry", "age": 26, "hobbies": ["coding", "reading"]}'

# Parse JSON string to Python dictionary
data = json.loads(json_data)

print("Name:", data["name"])  # Lucy Berry
print("Age:", data["age"])    # 26
print("Hobbies:", data["hobbies"])  # ['coding', 'reading']

βœ… Explanation:

  • json.loads() parses the JSON string into a Python dictionary.
  • You can access data using key-value pairs.

πŸ“© 3. Converting Python to JSON (Serialization/Encoding)

To convert Python objects back to JSON, use:

json.dumps()  # Convert Python object to JSON string

🎯 Example: Convert Python Dictionary to JSON String

import json

# Python dictionary
user_data = {
    "name": "Lucy Berry",
    "age": 26,
    "hobbies": ["coding", "reading"]
}

# Convert Python dictionary to JSON string
json_string = json.dumps(user_data)

print("JSON Data:", json_string)

βœ… Explanation:

  • json.dumps() converts the Python dictionary into a JSON string.

πŸ“š 4. Working with JSON Files in Python

πŸ“₯ a) Reading JSON from a File

To read JSON from a file and parse it into a Python object:

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

🎯 Example: Reading JSON File

import json

# Open and read JSON file
with open("user_data.json", "r") as file:
    data = json.load(file)

print("User Name:", data["name"])
print("User Age:", data["age"])

βœ… Explanation:

  • json.load() reads and parses JSON from a file.
  • The data is now a Python dictionary.

πŸ“€ b) Writing JSON to a File

To write Python data to a JSON file:

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

🎯 Example: Writing JSON to File

import json

# Python dictionary
user_data = {
    "name": "Lucy Berry",
    "age": 26,
    "hobbies": ["coding", "reading"]
}

# Write data to JSON file
with open("user_data.json", "w") as file:
    json.dump(user_data, file, indent=4)

print("Data successfully written to file!")

βœ… Explanation:

  • json.dump() writes JSON data to a file.
  • indent=4 formats the output for better readability.

πŸ•ΉοΈ 5. Pretty Print JSON in Python

To make JSON more readable, use indent in json.dumps():


🎯 Example: Pretty Print JSON

import json

# Python dictionary
user_data = {
    "name": "Lucy Berry",
    "age": 26,
    "hobbies": ["coding", "reading"]
}

# Pretty print JSON
pretty_json = json.dumps(user_data, indent=4)
print(pretty_json)

βœ… Explanation:

  • indent=4 makes the JSON easy to read with proper spacing.

πŸ”„ 6. Handling Nested JSON in Python

When you have complex JSON with nested objects or arrays, you can parse them easily.


🎯 Example: Parsing Nested JSON

import json

# Nested JSON string
nested_json = '''
{
  "name": "Lucy Berry",
  "address": {
    "street": "123 Snoopy Lane",
    "city": "Fukuoka",
    "country": "Japan"
  },
  "hobbies": ["coding", "reading"],
  "education": [
    {"degree": "Bachelors", "year": 2015},
    {"degree": "Masters", "year": 2019}
  ]
}
'''

# Parse nested JSON
data = json.loads(nested_json)

# Access nested objects
print("Street:", data["address"]["street"])
print("City:", data["address"]["city"])

# Access list of objects
for edu in data["education"]:
    print(f"{edu['degree']} - {edu['year']}")

βœ… Explanation:

  • Nested objects and arrays can be accessed using multiple keys.
  • Use loops to iterate through lists.

🧩 7. Converting Python Objects to JSON

json.dumps() works on many Python objects, including:

🐍 Python Object πŸ”₯ JSON Equivalent
dict Object
list, tuple Array
str String
int, float Number
True true
False false
None null

🎯 Example: Convert Different Python Objects to JSON

import json

# Data types to JSON
data = {
    "name": "Lucy Berry",
    "age": 26,
    "isAdmin": True,
    "hobbies": ["coding", "reading"],
    "pets": None
}

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

βœ… Explanation:

  • Different Python objects are automatically converted to valid JSON.

πŸ“‘ 8. Using JSON in APIs with Python

When interacting with APIs, you often send and receive JSON data.


🎯 Example: Sending JSON with requests Library

import requests
import json

# API URL
url = "https://api.example.com/users"

# Data to send
data = {
    "name": "Lucy Berry",
    "age": 26
}

# Send POST request with JSON data
response = requests.post(url, json=data)

# Print server response
print("Response:", response.json())

βœ… Explanation:

  • requests.post() sends a POST request with JSON.
  • response.json() parses the response.

⚑ 9. Error Handling in JSON with Python

When working with JSON, handle errors gracefully.


🎯 Example: Handling JSON Parsing Errors

import json

# Invalid JSON string
invalid_json = '{"name": "Lucy", "age": 26,}'

try:
    data = json.loads(invalid_json)
    print("Parsed Data:", data)
except json.JSONDecodeError as e:
    print("Error parsing JSON:", e)

βœ… Explanation:

  • json.JSONDecodeError catches invalid JSON.
  • Proper error handling prevents crashes.

🧠 10. Customizing JSON Encoding in Python

You can define how custom objects are converted to JSON.


🎯 Example: Custom JSON Encoder

import json

# Custom class
class User:
    def __init__(self, name, age):
        self.name = name
        self.age = age

# Custom encoder
class UserEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, User):
            return {"name": obj.name, "age": obj.age}
        return super().default(obj)

# Create user instance
user = User("Lucy Berry", 26)

# Encode with custom encoder
json_data = json.dumps(user, cls=UserEncoder)
print(json_data)

βœ… Explanation:

  • UserEncoder defines how to convert User objects to JSON.

πŸ”₯ 11. Advanced: JSON Path in Python

To extract specific data from JSON, use the jsonpath library.


🎯 Example: Using JSONPath

import json
import jsonpath

# JSON data
data = '''
{
  "users": [
    {"name": "Lucy", "age": 26},
    {"name": "Bruce", "age": 35}
  ]
}
'''

# Parse JSON
parsed_data = json.loads(data)

# Extract all names
names = jsonpath.jsonpath(parsed_data, "$.users[*].name")
print(names)  # ['Lucy', 'Bruce']

βœ… Explanation:

  • $.users[*].name extracts all names from the JSON.