Working With JSON
JSON is one of the most important data formats used in modern applications. APIs, web applications, configuration files, and AI systems frequently use JSON to exchange structured data.
JSON is a structured way to store and exchange data.
Python can convert JSON into normal Python objects and convert Python objects back into JSON. This makes it easy to work with data received from APIs or stored in files.
What Is JSON?
JSON stands for JavaScript Object Notation.
Despite its name, JSON is not limited to JavaScript. Almost every modern programming language can work with JSON.
A simple JSON object looks like this:
{
"name": "John",
"age": 30,
"is_student": false
}
Here we have three pieces of information:
name→ textage→ numberis_student→ true or false
JSON Data Types
JSON supports several basic data types.
String → "John"
Number → 30
Boolean → true / false
Null → null
Array → ["Python", "AI"]
Object → {"name": "John"}
JSON objects use curly braces
{ }.
JSON arrays use square brackets
[ ].
JSON Object
A JSON object contains key-value pairs.
{
"name": "Alice",
"age": 25,
"city": "London"
}
Think of it like a Python dictionary:
person = {
"name": "Alice",
"age": 25,
"city": "London"
}
The structure looks very similar, but JSON and a Python dictionary are not exactly the same thing.
JSON Arrays
JSON arrays are similar to Python lists.
{
"languages": [
"Python",
"JavaScript",
"Java"
]
}
In Python, this becomes a list when JSON is converted into Python data.
data = {
"languages": [
"Python",
"JavaScript",
"Java"
]
}
Python's json Module
Python provides a built-in module called
json.
import json
The two most important concepts are:
JSON → Python json.loads() Python → JSON json.dumps()
Remember the difference:
-
loads()means load JSON from a string. -
dumps()means convert Python data into a JSON string.
Converting JSON to Python
Suppose an API sends this JSON:
{
"name": "John",
"age": 30
}
We can store it as a string and convert it into a Python dictionary.
import json
json_data = '''
{
"name": "John",
"age": 30
}
'''
person = json.loads(json_data)
print(person)
{'name': 'John', 'age': 30}
Now person is a normal Python dictionary.
Accessing JSON Data
After converting JSON into a Python dictionary, you can access values using their keys.
import json
json_data = '''
{
"name": "John",
"age": 30
}
'''
person = json.loads(json_data)
print(person["name"])
print(person["age"])
John 30
Converting Python to JSON
Sometimes your Python program needs to send data to an API.
In that situation, you may need to convert Python data into JSON.
import json
person = {
"name": "John",
"age": 30
}
json_data = json.dumps(person)
print(json_data)
{"name": "John", "age": 30}
The Python dictionary has now been converted into a JSON string.
Pretty Printing JSON
By default, JSON can appear on one line. You can make
it easier to read using indent.
import json
person = {
"name": "John",
"age": 30,
"skills": [
"Python",
"AI"
]
}
print(
json.dumps(
person,
indent=4
)
)
{
"name": "John",
"age": 30,
"skills": [
"Python",
"AI"
]
}
Reading a JSON File
JSON is also commonly stored inside a
.json file.
Create a file called user.json:
{
"name": "Alice",
"age": 25,
"skills": [
"Python",
"AI"
]
}
Python can read the file using
json.load().
import json
with open(
"user.json",
"r",
encoding="utf-8"
) as file:
user = json.load(file)
print(user["name"])
print(user["skills"])
Alice ['Python', 'AI']
Notice the difference:
json.loads()
↓
JSON string → Python object
json.load()
↓
JSON file → Python object
Writing JSON to a File
You can also save Python data into a JSON file.
import json
user = {
"name": "Alice",
"age": 25,
"skills": [
"Python",
"AI"
]
}
with open(
"user.json",
"w",
encoding="utf-8"
) as file:
json.dump(
user,
file,
indent=4
)
The important difference is:
json.dumps()
↓
Python → JSON string
json.dump()
↓
Python → JSON file
Nested JSON
Real-world JSON is often nested. That means an object can contain other objects or arrays.
{
"user": {
"name": "John",
"address": {
"city": "London",
"country": "UK"
}
}
}
After loading it into Python, you can access nested values step by step.
import json
data = json.loads('''
{
"user": {
"name": "John",
"address": {
"city": "London",
"country": "UK"
}
}
}
''')
print(data["user"]["name"])
print(
data["user"]["address"]["city"]
)
John London
JSON and APIs
JSON becomes especially important when working with APIs.
For example, an API might return:
{
"id": 101,
"name": "Laptop",
"price": 1200
}
Python can receive this data and work with it.
product = {
"id": 101,
"name": "Laptop",
"price": 1200
}
print(product["name"])
print(product["price"])
Laptop 1200
This is why understanding JSON is essential before working deeply with APIs and AI services.
JSON in AI Applications
AI applications commonly use JSON to send structured requests and receive structured responses.
For example, an AI application might work with data like this:
{
"question": "What is Python?",
"language": "English"
}
Your Python application can read the values:
request = {
"question": "What is Python?",
"language": "English"
}
question = request["question"]
language = request["language"]
print(question)
print(language)
What is Python? English
Handling Invalid JSON
JSON received from an external system may be invalid.
Attempting to parse invalid JSON can raise
JSONDecodeError.
import json
json_data = '''
{
"name": "John",
"age":
}
'''
try:
data = json.loads(json_data)
print(data)
except json.JSONDecodeError:
print("Invalid JSON")
Invalid JSON
This is especially useful when processing data received from APIs or external files.
JSON vs Python Dictionary
Beginners often confuse JSON with a Python dictionary. They look similar, but they are different things.
Python Dictionary
{
"name": "John",
"age": 30
}
↓ json.dumps()
JSON String
'{"name": "John", "age": 30}'
A Python dictionary is a Python object in memory. JSON is a data format used for storing or exchanging structured data.
Mini Project — AI User Data Processor
Let's build a small program that reads user information from a JSON file and prepares the data for an AI application.
Create this structure:
project/ │ ├── main.py │ └── user.json
Put this inside user.json:
{
"name": "John",
"age": 30,
"interests": [
"Python",
"AI",
"Machine Learning"
]
}
Now create main.py:
import json
with open(
"user.json",
"r",
encoding="utf-8"
) as file:
user = json.load(file)
name = user["name"]
age = user["age"]
interests = user["interests"]
print("Name:", name)
print("Age:", age)
print("Interests:", interests)
Name: John Age: 30 Interests: ['Python', 'AI', 'Machine Learning']
Now the application has structured Python data that can be passed to another part of the application or an AI service.
The Four JSON Functions to Remember
json.loads() JSON string → Python object json.dumps() Python object → JSON string json.load() JSON file → Python object json.dump() Python object → JSON file
If you remember these four functions, you can handle most basic JSON operations in Python.
What You Learned
- What JSON is
- JSON data types
- JSON objects and arrays
- Using Python's
jsonmodule - Converting JSON strings into Python objects
- Converting Python objects into JSON strings
- Reading JSON files
- Writing JSON files
- Working with nested JSON
- Using JSON with APIs
- Using JSON in AI applications
- Handling invalid JSON
- The difference between JSON and dictionaries
JSON is the bridge between Python applications and external data.
APIs, web applications, configuration files, and AI
services commonly exchange structured information using
JSON. Learn to move comfortably between JSON and Python
dictionaries, lists, and other objects using
load(), loads(),
dump(), and dumps().