JSON
JSON is one of the most important data formats used by APIs. In this lesson, you will learn what JSON is, how JSON represents data, how JSON relates to Python dictionaries and lists, and how to work with JSON in Python.
JSON is a standard way to exchange structured data.
When two different applications need to communicate, they need a common format for exchanging information. JSON provides that common format. Python can convert JSON into Python objects and Python objects back into JSON.
What Is JSON?
JSON stands for JavaScript Object Notation.
Despite its name, JSON is not limited to JavaScript. It is widely used by Python, PHP, Java, JavaScript, mobile applications, AI applications, and many other technologies.
JSON is mainly used to represent and exchange structured data.
{
"name": "John",
"age": 25,
"is_student": true
}
This represents information about a person.
Why Do We Need JSON?
Imagine a Python application communicating with a different application written in JavaScript.
Python and JavaScript have different internal data structures. They need a common format that both applications understand.
Python Application
↓
JSON
↓
Other Application
↓
JSON
↓
Python Application
JSON acts as a common language for exchanging structured information.
JSON Object
A JSON object is surrounded by curly braces:
{ }.
{
"name": "John",
"age": 25,
"country": "India"
}
JSON stores information using key-value pairs.
"name": "John" ↑ ↑ key value
Here:
nameis the key.Johnis the value.
JSON Data Types
JSON supports several basic types of values.
{
"name": "John",
"age": 25,
"price": 99.50,
"active": true,
"address": null
}
The main JSON types are:
- String
- Number
- Boolean
- Object
- Array
- null
JSON uses lowercase
true,
false, and
null.
JSON Arrays
A JSON array stores multiple values and uses square
brackets:
[ ].
{
"name": "John",
"skills": [
"Python",
"NumPy",
"Pandas"
]
}
The skills value contains multiple items.
JSON arrays are similar to Python lists.
JSON Array
↓
[ "Python", "NumPy", "Pandas" ]
Python List
↓
["Python", "NumPy", "Pandas"]
JSON vs Python
JSON looks very similar to Python dictionaries, but they are not exactly the same thing.
JSON
{
"name": "John",
"age": 25,
"active": true
}
Python Dictionary
{
"name": "John",
"age": 25,
"active": True
}
Notice the difference:
JSON: true Python: True
JSON is a data format. A Python dictionary is a Python data structure.
JSON as a String
JSON can be represented as text.
json_data = '{"name": "John", "age": 25}'
Here, json_data is a Python string containing
JSON.
Python does not automatically treat that string as a dictionary.
print(type(json_data))
<class 'str'>
We need to convert it into a Python object.
Convert JSON String to Python
Python provides the built-in json module
for working with JSON.
import json
json_data = '{"name": "John", "age": 25}'
person = json.loads(json_data)
print(person)
json.loads() means:
load JSON from a string.
JSON String
↓
json.loads()
↓
Python Dictionary
Now you can access the values normally:
print(person["name"]) print(person["age"])
John 25
Convert Python to JSON
The opposite operation is also common.
We can convert a Python dictionary into a JSON string
using json.dumps().
import json
person = {
"name": "John",
"age": 25
}
json_data = json.dumps(person)
print(json_data)
{"name": "John", "age": 25}
Python Dictionary
↓
json.dumps()
↓
JSON String
loads() vs dumps()
These two functions are easy to confuse, so remember the direction.
json.loads()
JSON string → Python object
person = json.loads(json_data)
json.dumps()
Python object → JSON string
json_data = json.dumps(person)
JSON ↓ loads() ↓ Python Python ↓ dumps() ↓ JSON
Working With JSON Files
JSON is also commonly stored in files.
Example file:
user.json
Contents:
{
"name": "John",
"age": 25,
"skills": [
"Python",
"AI"
]
}
Python can read this file using
json.load().
import json
with open("user.json", "r") as file:
user = json.load(file)
print(user["name"])
print(user["skills"])
Notice that this is load(), not
loads().
json.load()
↓
Reads JSON from a file
json.loads()
↓
Reads JSON from a string
Writing JSON to a File
Python can also save a dictionary as a JSON file.
import json
user = {
"name": "John",
"age": 25,
"skills": [
"Python",
"AI"
]
}
with open("user.json", "w") as file:
json.dump(user, file, indent=4)
json.dump() writes Python data directly
into a JSON file.
The indent=4 makes the file easier for
humans to read.
JSON With Requests
This is where JSON becomes important for API development.
When you call an API with Requests, the server may return JSON.
import requests
response = requests.get(
"https://httpbin.org/json"
)
data = response.json()
print(data)
Requests provides response.json() to
convert the JSON response into Python data.
API ↓ JSON Response ↓ response.json() ↓ Python Dictionary / List
You normally do not need to call
json.loads() yourself when Requests has
already parsed the response for you.
Sending JSON With Requests
APIs also commonly expect JSON in the request body.
import requests
data = {
"name": "John",
"age": 25
}
response = requests.post(
"https://httpbin.org/post",
json=data
)
print(response.json())
The important part is:
json=data
Requests converts the Python data into JSON and sends it as part of the HTTP request.
Python Dictionary
↓
Requests
↓
JSON
↓
POST Request
↓
API
Nested JSON
Real APIs often return more complicated JSON structures.
{
"user": {
"name": "John",
"age": 25,
"address": {
"city": "Hyderabad",
"country": "India"
}
}
}
In Python, you can access nested values using multiple dictionary keys.
data["user"]["name"] data["user"]["address"]["city"]
Example:
print(data["user"]["name"]) print(data["user"]["address"]["city"])
John Hyderabad
JSON Arrays of Objects
APIs frequently return a list of objects.
{
"products": [
{
"id": 1,
"name": "Laptop",
"price": 800
},
{
"id": 2,
"name": "Phone",
"price": 500
}
]
}
In Python:
products = data["products"]
for product in products:
print(product["name"])
print(product["price"])
Laptop 800 Phone 500
This pattern is extremely common when consuming APIs.
Why JSON Is Important for AI
Modern AI applications communicate with models and services through APIs. Those APIs commonly use JSON for requests and responses.
Python AI Application
↓
JSON Request
↓
AI API
↓
AI Model
↓
JSON Response
↓
Python Application
A simplified AI request might look like this:
{
"model": "example-model",
"messages": [
{
"role": "user",
"content": "Explain Python"
}
]
}
The exact structure depends on the API provider, but the important concept remains the same: structured data is exchanged as JSON.
Complete Python Example
Let's combine JSON conversion and API communication.
import requests
import json
data = {
"name": "John",
"age": 25,
"skills": [
"Python",
"AI"
]
}
json_string = json.dumps(data)
print("JSON:")
print(json_string)
response = requests.post(
"https://httpbin.org/post",
json=data,
timeout=10
)
response.raise_for_status()
result = response.json()
print("\nResponse:")
print(result)
The complete flow is:
Python Dictionary
↓
json.dumps()
↓
JSON String
Python Dictionary
↓
Requests
↓
POST Request
↓
API
↓
JSON Response
↓
response.json()
↓
Python Dictionary
Common Mistake
One common beginner mistake is confusing JSON with a Python dictionary.
Python
user = {
"name": "John",
"active": True
}
JSON
{
"name": "John",
"active": true
}
They look almost identical, but Python and JSON have different rules.
The easiest way to remember this is:
Python Dictionary
≠
JSON
Python Dictionary
↕
Conversion
↕
JSON
What You Learned
- What JSON means
- Why applications use JSON
- JSON objects
- JSON arrays
- JSON data types
- JSON vs Python dictionaries
json.loads()json.dumps()json.load()json.dump()- Reading JSON files
- Writing JSON files
- Working with JSON through Requests
- Nested JSON
- Arrays of JSON objects
- Why JSON is important for AI APIs
JSON is the common language used to exchange structured data between applications.
In Python, you will constantly move between Python dictionaries/lists and JSON when working with APIs. Remember the basic flow: Python data → JSON → API → JSON → Python data. This pattern becomes fundamental when you start working with LLM and AI APIs.