The syntax for JSON is very similar to that of a Python dictionary.
{} hold objects.[] hold arrays (lists).This is a valid JSON string.
Notice the structure:
{}."students".[] of other JSON objects.{
"students": [
{
"id": 1,
"name": "Tim",
"age": 21,
"full-time": true
},
{
"id": 2,
"name": "Joe",
"age": 24,
"full-time": false
}
]
}
In JSON, you MUST use double quotation marks (" ") for keys and string values.
Single quotes (' ') are not permitted and will cause an error.
JSON is widely used for:
json ModulePython has a built-in library for working with JSON data.
# Import the built-in json library
import json
You can "load" a JSON string into a Python object (specifically, a dictionary).
The function to use is json.loads().
The "s" in loads stands for "string".
# 's' is for string
json.loads(json_string)
json.loads()Pass a valid JSON string to json.loads().
The result is a Python dictionary that you can work with directly.
import json
json_string = '{"name": "Tim", "age": 21}'
# Load the string into a Python dictionary
data = json.loads(json_string)
print(data)
# Output: {'name': 'Tim', 'age': 21}
print(type(data))
# Output: <class 'dict'>
Once loaded, the data behaves just like a regular Python dictionary or list.
You can use standard key and index lookups to access nested values.
# Assuming 'data' is the loaded object from the
# larger JSON example
# Get the list of students
all_students = data['students']
# Get the first student in the list
first_student = data['students'][0]
# Get the name of the first student
name = data['students'][0]['name']
print(name)
# Output: Tim
You can also "dump" a Python dictionary into a JSON formatted string.
The function to use is json.dumps().
Again, the "s" in dumps stands for "string".
# 's' is for string
json.dumps(python_dictionary)
json.dumps()Pass a Python dictionary to json.dumps() to get a JSON-formatted string as a result.
Note how Python's True boolean becomes JSON's true.
import json
data = {
'name': 'Joe',
'age': 24,
'full-time': True
}
# Dump the dictionary into a JSON string
new_json = json.dumps(data)
print(new_json)
# Output: {"name": "Joe", "age": 24, "full-time": true}
When dumping to a string, the default output is compact and not very readable.
You can use the indent argument to "pretty-print" the JSON, making it much easier for humans to read.
# Use the indent argument
# A value of 2 or 4 is common.
json.dumps(data, indent=4)
indent ExampleUsing indent=4 adds newlines and 4-space indents to create a nicely formatted string.
new_json = json.dumps(data, indent=4)
print(new_json)
# Output:
# {
# "name": "Joe",
# "age": 24,
# "full-time": true
# }
You can also ensure the keys in your JSON output are in alphabetical order using the sort_keys argument.
This is useful for making JSON output consistent and easier to compare.
new_json = json.dumps(data, indent=4, sort_keys=True)
print(new_json)
# Output:
# {
# "age": 24,
# "full-time": true,
# "name": "Joe"
# }
The json library provides similar functions for reading from and writing to files directly.
json.load() (no 's')json.dump() (no 's')These functions work with file objects, not strings.
First, open the file in read mode ('r'). Then, pass the file object to json.load().
This is the standard and safest way to handle files in Python.
import json
# Assumes a file named 'data.json' exists
with open('data.json', 'r') as f:
my_data = json.load(f)
print(my_data)
To write a Python dictionary to a JSON file, you use json.dump().
json.dump(), passing it two arguments:
This example takes our `data` dictionary and saves it to a new file named `data2.json`.
The formatting arguments like indent also work with json.dump().
import json
# The dictionary we want to save
data = {
'name': 'Joe',
'age': 24,
'full-time': True
}
with open('data2.json', 'w') as f:
json.dump(data, f, indent=4)
# A file named 'data2.json' is now created
# with the formatted JSON content.
JSON is ideal for creating a digital library or a Bill of Materials (BOM) by storing electronic component specifications in a structured way.
This allows for easy parsing, searching, and integration with design or simulation software.
# Python dictionary representing a microcontroller
atmega328p = {
"part_number": "ATMEGA328P-PU",
"manufacturer": "Microchip",
"category": "Microcontroller",
"package": "PDIP-28",
"specs": {
"flash_memory_kb": 32,
"ram_kb": 2,
"pins": 28,
"operating_voltage": "1.8V - 5.5V"
}
}
# Convert to a readable JSON string for a database
component_json = json.dumps(atmega328p, indent=4)
print(component_json)
In automated testing, JSON is used to define test configurations and log results from instruments like oscilloscopes or power supplies.
This creates a clear, machine-readable record of every test run.
# Python dictionary of test results for a power amplifier
test_results = {
"test_id": "PA-GAIN-SWEEP-001",
"timestamp": "2023-10-27T14:30:15Z",
"device_under_test": "RF-AMP-78B",
"measurements": [
{"frequency_mhz": 100, "gain_db": 10.2, "status": "PASS"},
{"frequency_mhz": 500, "gain_db": 9.8, "status": "PASS"},
{"frequency_mhz": 900, "gain_db": 8.5, "status": "FAIL"}
]
}
# Dump results to a log file
with open('test_run_001.json', 'w') as log_file:
json.dump(test_results, log_file, indent=2)
IoT devices, like environmental sensors, send data to servers using JSON. It is lightweight, making it efficient for network transmission (e.g., over MQTT or HTTP).
import datetime
# Data from a hypothetical weather sensor node
sensor_payload = {
"device_id": "WEATHER-STN-04",
"timestamp": datetime.datetime.now().isoformat(),
"location": {
"lat": 34.0522,
"lon": -118.2437
},
"sensor_readings": {
"temperature_c": 22.5,
"humidity_rh": 55.2,
"pressure_hpa": 1012.5
}
}
# Convert to a compact JSON string for network sending
json_payload = json.dumps(sensor_payload)
print(json_payload)
Let's put your knowledge to the test!
pcb_design.json.This file represents basic metadata for a Printed Circuit Board design.
{
"project_name": "Audio Amplifier v1",
"version": 1.0,
"designer": "Alex Ray",
"is_finalized": false,
"dimensions_mm": {
"width": 100,
"height": 75
},
"layers": 2,
"components": [
{
"designator": "U1",
"part_number": "LM386",
"description": "Low Voltage Audio Power Amplifier"
},
{
"designator": "C1",
"part_number": "CAP-ELEC-100uF",
"description": "100uF Electrolytic Capacitor"
},
{
"designator": "R1",
"part_number": "RES-10K-OHM",
"description": "10k Ohm Resistor"
}
]
}
Write a Python script that performs the following steps:
pcb_design.json file.version to 1.1.is_finalized status to True.components list.pcb_design_v2.json. Make sure the output is nicely formatted with an indent of 4.API stands for Application Programming Interface. At its core, an API is a set of rules, definitions, and protocols that allow different software applications to communicate with each other.
Think of it as a waiter in a restaurant:
The API is the intermediary that lets you get what you need from the server without having to know how the kitchen works.
APIs solve fundamental challenges in software development by enabling interoperability and efficiency.
API communication follows a standard client-server model based on a request and a response.
A typical web API request (over HTTP) is made up of several key parts:
After processing a request, the server sends back a response with the following components:
JSON (JavaScript Object Notation) is the most common data format for APIs. It is lightweight, text-based, and easy for both humans and machines to read and write.
It represents data as a collection of key-value pairs, similar to a Python dictionary.
{
"user": {
"id": 123,
"username": "api_user",
"email": "user@example.com",
"isActive": true,
"roles": [
"editor",
"contributor"
]
}
}
While the concept is universal, APIs can be designed using different architectural styles.
You interact with APIs every day, often without realizing it.
This API retrieves current weather data for a specified location. The client sends a GET request with the city name and an API key as parameters in the URL.
The server responds with a JSON object containing the requested weather information.
Example Response (JSON):
{'location': {'name': 'Auckland',
'region': '',
'country': 'New Zealand',
'lat': -36.8667,
'lon': 174.7667,
'tz_id': 'Pacific/Auckland',
'localtime_epoch': 1756313420,
'localtime': '2025-08-28 04:50'},
'current': {'last_updated_epoch': 1756313100,
'last_updated': '2025-08-28 04:45',
'temp_c': 8.4,
'temp_f': 47.1,
'is_day': 0, ...}
# Using Python's 'requests' library
import requests
import json
# --- 1. The Request ---
API_KEY = "your_actual_api_key"
city = "London"
url = f"http://api.weatherapi.com/v1/current.json?key={API_KEY}&q={city}&aqi=no"
response = requests.get(url)
# --- 2. The Response ---
if response.status_code == 200:
data = response.json()
temp_celsius = data['current']['temp_c']
print(f"Temperature in {city}: {temp_celsius:.2f}°C")
else:
print(f"Error: {response.status_code}")
A payment API like Stripe allows you to process payments securely. Here, we send a POST request to create a "Payment Intent," signaling our intent to collect a payment.
The request body contains details like amount and currency. The API responds with a secure client secret that the frontend uses to complete the payment.
Example Response (JSON):
{
"id": "pi_3L...",
"object": "payment_intent",
"amount": 2000,
"currency": "usd",
"status": "requires_payment_method",
"client_secret": "pi_3L..._secret_5m..."
}
# Using the official Stripe Python library
import stripe
# --- 1. The Request ---
stripe.api_key = "your_secret_stripe_key"
try:
# Create a PaymentIntent on the server
intent = stripe.PaymentIntent.create(
amount=2000, # Amount in cents ($20.00)
currency="usd",
automatic_payment_methods={"enabled": True},
)
# --- 2. The Response ---
# Send the client_secret back to the frontend
print({
'clientSecret': intent.client_secret
})
except stripe.error.StripeError as e:
print(f"Stripe Error: {e}")
Generative AI APIs, like OpenAI's DALL-E, create content based on a prompt. The client sends a POST request with a JSON body containing the text prompt and other options (like image size).
The API processes the prompt and responds with a URL pointing to the newly generated image.
Example Response (JSON):
{
"created": 1686940366,
"data": [
{
"url": "https://oaidalleapiprodscus.blob.core.windows.net/..."
}
]
}
# Using Python's 'requests' library
import requests
import json
import os
import PIL
import io
# --- 1. The Request ---
API_KEY = "your_openai_api_key"
url = "https://api.openai.com/v1/images/generations"
headers = {
"Authorization": f"Bearer {API_KEY}",
"Content-Type": "application/json"
}
body = {
"prompt": "a photo of a happy corgi wearing a cowboy hat",
"n": 1,
"size": "1024x1024"
}
response = requests.post(url, headers=headers, json=body)
# --- 2. The Response ---
if response.status_code == 200:
data = response.json()
image_url = data['data'][0]['url']
print(f"Image generated successfully!")
print(f"URL: {image_url}")
# Get the image data from the URL
image_response = requests.get(image_url)
# Raise an exception if the download failed
image_response.raise_for_status()
# Open the image from the in-memory bytes
image_bytes = io.BytesIO(image_response.content)
img = Image.open(image_bytes)
# Display the image (will open in your default image viewer)
print("Displaying image...")
img.show(title="Generated Corgi")
else:
print(f"Error: {response.status_code}")
print(response.text)