-
Hajipur, Bihar, 844101
JSON is a popular format used to store and share data. Many websites, apps and APIs use JSON because it is simple, readable and works well with almost every programming language. Python has built-in support for JSON, which makes it easy to read data from a file, convert Python objects into JSON and work with real-world data.
In this tutorial, you will learn what JSON is, how to handle JSON in Python, how to convert between Python objects and JSON strings, how to read and write JSON files and how JSON is used in real projects.
JSON stands for JavaScript Object Notation. It is a text-based format used to store structured data. Even though its name contains “JavaScript,” JSON is not limited to JavaScript. It is used everywhere, from mobile apps to online dashboards.
JSON is known for:
simple formatting
easy readability
support for key-value data
compatibility with many languages
Example of JSON data:
{
"name": "Aarohi",
"age": 20,
"city": "Delhi"
}
JSON is used because it is lightweight, easy to understand and works well across platforms. Many services send responses in JSON, and Python developers need to know how to read and use this data.
Common uses:
APIs return data in JSON
Apps store settings in JSON
Databases store documents in JSON format
Websites exchange data using JSON
Python has a built-in module called json that provides many functions for converting data between JSON and Python objects.
You do not need to install anything. Just import and begin using it.
import json
You can convert Python objects into JSON strings using json.dumps().
Example:
import json
data = {
"name": "Bhoomi",
"age": 18,
"course": "Python"
}
result = json.dumps(data)
print(result)
This converts the Python dictionary into a JSON formatted string.
You can format JSON output using the indent parameter.
print(json.dumps(data, indent=4))
This makes the output easier to read.
JSON strings can be converted into Python objects using json.loads().
Example:
import json
json_text = '{"name":"Kavya", "age":19, "city":"Mumbai"}'
result = json.loads(json_text)
print(result)
print(result["city"])
Python converts JSON objects into dictionaries, JSON arrays into lists and JSON values into their nearest Python type.
Python interprets JSON data like this:
JSON object → Python dict
JSON array → Python list
JSON string → Python str
JSON number → Python int or float
JSON true/false → Python True/False
JSON null → Python None
JSON files are common in real projects. You can read them using json.load().
Example:
import json
with open("data.json", "r") as file:
info = json.load(file)
print(info)
This is useful for reading API responses stored in files or configuration settings.
To store data in a file, use json.dump().
Example:
import json
data = {"name": "Tara", "marks": 85}
with open("student.json", "w") as file:
json.dump(data, file, indent=4)
This saves the dictionary as a JSON file.
JSON supports nested objects and lists, just like Python.
Example:
json_text = '''
{
"team": "Developers",
"members": [
{"name": "Aarohi", "role": "Backend"},
{"name": "Bhoomi", "role": "Frontend"}
]
}
'''
data = json.loads(json_text)
print(data["members"][1]["role"])
Nested JSON is very common when working with APIs.
Sometimes JSON data may be invalid. You can use try...except to catch errors.
import json
text = "{name: 'Aarohi'}" # invalid JSON
try:
data = json.loads(text)
except json.JSONDecodeError:
print("Invalid JSON")
This helps you avoid crashes during parsing.
Imagine an API returns this JSON:
{
"product": "Laptop",
"price": 45000,
"in_stock": true
}
You can handle it in Python like this:
import json
response = '{"product":"Laptop","price":45000,"in_stock":true}'
data = json.loads(response)
print(data["product"])
print(data["price"])
print(data["in_stock"])
This is how e-commerce, travel and news apps use live data.
Convert dictionary to JSON
import json
print(json.dumps({"country": "India"}))
Pretty print JSON
json.dumps(data, indent=4)
Load JSON string
json.loads('{"a":1}')
Read JSON file
with open("data.json") as f:
print(json.load(f))
Write JSON file
json.dump(data, open("info.json", "w"))
Nested JSON
print(data["members"][0]["name"])
Convert list to JSON
json.dumps(["apple", "banana"])
Convert JSON array to list
json.loads('["x","y"]')
Change JSON indentation
json.dumps(data, indent=2)
Handle invalid JSON
try:
json.loads("{bad json}")
except:
print("Error")
JSON is one of the most widely used formats for data sharing. Python makes it easy to convert data to and from JSON using the built-in json module. You learned how to read JSON, write JSON files, format JSON output, work with nested data and handle errors. JSON plays an important role in APIs, apps and any project that needs structured data.
Q1. Write a Python program to convert a Python list to JSON using json.dumps().
Q2. Write a Python program to convert a JSON string to a dictionary using json.loads() and access a specific value.
Q3. Write a Python program to write a Python dictionary to a .json file using json.dump().
Q4. Write a Python program to read and print content from a .json file using json.load().
Q5. Write a Python program to create a Python object with mixed data types (int, str, list, bool) and convert it to JSON.
Q6. Write a Python program to use sort_keys=True in json.dumps() and show sorted key output.
Q7. Write a Python program to add pretty formatting to JSON output using indent=2 in json.dumps().
Q8. Write a Python program to convert Python None to JSON using json.dumps() and verify the result (null in JSON).
Q9. Write a Python program to store user information (like name, age) in a .json file.
Q10. Write a Python program to read JSON content from a file and loop through all dictionary keys.