JSON in Python

JSON in Python in Python: JSON (JavaScript Object Notation) is the way computers "talk" to each other today.

Concept Explanation

JSON (JavaScript Object Notation) is the way computers "talk" to each other today. Whether you're fetching weather data from Google or checking your account balance on a mobile app, the data is almost certainly moving through the internet in JSON format.

JSON is a lightweight data-interchange format that is easy for humans to read and write, and easy for machines to parse and generate. In Python, JSON looks almost exactly like a Dictionary, which makes working with it very intuitive.

Why use JSON?

  • Interoperability: Every programming language (Java, C++, JavaScript, etc.) understands JSON.
  • Web API Standard: It's the primary format for data transferred via Web APIs.
  • Human Readable: You can look at a JSON file and tell exactly what's inside.

Syntax or Core Structure

The json Module

Python has a built-in library called json to handle everything. You don't need to install anything!

There are four primary methods to remember:

  1. json.loads(string): Parse a JSON string into a Python Dictionary.
  2. json.load(file): Parse a JSON file into a Python Dictionary.
  3. json.dumps(dict): Convert a Python Dictionary into a JSON string.
  4. json.dump(dict, file): Save a Python Dictionary into a JSON file.

Code Example #1 (Basic)

Parsing a string into a dictionary and converting a dictionary back to a string.

import json

# 1. Parsing JSON (JSON string -> Python Dictionary)
json_string = '{"user": "Harsh", "is_admin": true, "points": 450}'
data = json.loads(json_string)

print(f"User Name: {data['user']}") # Harsh

# 2. Stringifying (Python Dictionary -> JSON string)
new_user = {
    "name": "Alice",
    "roles": ["Dev", "Admin"],
    "active": False
}

json_output = json.dumps(new_user, indent=4) # indent makes it look pretty!
print(json_output)

Code Example #2 (Intermediate)

Handling complex data types and formatting.

import json

data = {
    "project": "Syntax Stage",
    "version": 1.2,
    "features": ["Login", "Search", "Payment"],
    "is_public": None # This becomes 'null' in JSON
}

# Converting with specific formatting
json_formatted = json.dumps(
    data, 
    indent=4, 
    separators=(". ", " = "), # Customizing separators
    sort_keys=True            # Alphabetical order
)

print(json_formatted)

Real World Example

Loading API Config: Imagine your app needs to load its configuration from a settings.json file.

import json
import os

# 📂 Mock Settings File Creation
with open("settings.json", "w") as f:
    json.dump({"theme": "dark", "vol": 75, "auto_save": True}, f)

# 📖 Reading the JSON file
def load_settings():
    if os.path.exists("settings.json"):
        with open("settings.json", "r") as f:
            config = json.load(f)
            return config
    return {}

user_config = load_settings()
print(f"Current Theme: {user_config.get('theme')}")

Common Mistakes

  1. Confusing load vs loads: Remember: load is for files, loads is for strings (the 's' stands for string).
  2. Single vs Double Quotes: JSON strictly requires double quotes (") for keys and strings. Python allows single quotes ('), so copy-pasting a Python dict into a JSON file often fails.
  3. Non-Serializable Objects: You cannot convert a custom Python Class object directly to JSON without a special "encoder". Only basic types (dict, list, str, int, float, bool, None) work automatically.

Best Practices

  • Use Indentation: When writing JSON to files or printing for logs, always use indent=4 so humans can read it easily.
  • Graceful Parsing: JSON parsing can fail if the string is malformed. Always use a try...except json.JSONDecodeError block.
  • Keys must be Strings: In JSON, keys must be strings. If your Python dictionary has integer keys, json.dumps will convert them to strings automatically.

Practice Exercises

  1. The Profile Builder: Create a dictionary with your name, age, and a list of hobbies. Convert it to a JSON string with an indentation of 2.
  2. API Simulator: Take the string {"status": "success", "data": [10, 20, 30]}. Parse it and print the average of the numbers in the "data" list.
  3. Config Saver: Write a Python dictionary to a file called config.json and then read it back to verify the content.