In this Python JSON tutorial, we will learn how to parse JSON strings and files, access nested objects and arrays, convert Python objects to JSON, format JSON output, handle decoding errors, and serialize custom data types with practical examples.
Python JSON Tutorial
JSON, or JavaScript Object Notation, is a text format used to store and exchange structured data. It is commonly used in web APIs, configuration files, application data, and communication between services.
Python includes the built-in json module for converting between JSON text and Python objects. No third-party package is required.
Import the Python json Module
json package comes inbuilt with Python. So, all you have to do to use json package is, import at the start of your program.
To import json into your Python program, use the following import statement.
import json
The four main functions used in this module are:
json.loads()parses a JSON string and returns a Python object.json.load()reads JSON from a file-like object.json.dumps()converts a Python object to a JSON string.json.dump()writes a Python object as JSON to a file-like object.
JSON Values and Their Python Equivalents
When Python decodes JSON, each JSON value is converted to a corresponding Python type.
| JSON value | Python type |
|---|---|
| object | dict |
| array | list |
| string | str |
| number without a fraction | int |
| number with a fraction | float |
true | True |
false | False |
null | None |
JSON object keys must be strings. JSON also uses lowercase true, false, and null, while Python uses True, False, and None.
Parse a JSON String and Access Elements
Consider the following JSON String.
{"rollno":25, "name":"Raghu", "class":7, "section":"B"}
We will parse this JSON string using loads() function of json module. And we shall print the individual elements of the JSON object.
Python Program
import json
#json string
jsonStr = '{"rollno":25, "name":"Raghu", "class":7, "section":"B"}'
#parse/load json string into json object
jsonObj = json.loads(jsonStr)
#access
print(jsonObj["rollno"])
print(jsonObj["name"])
print(jsonObj["class"])
print(jsonObj["section"])
Output
25
Raghu
7
B
As you can observe, once the JSON string is parsed to an object jsonObj, you can access the individual elements with key used as index.
For example, jsonObj["rollno"] returns the value for the key rollno in jsonObj.
Use dict.get() when a key may be missing and you want to avoid a KeyError.
import json
json_text = '{"name": "Raghu", "class": 7}'
student = json.loads(json_text)
print(student.get("name"))
print(student.get("section", "Not assigned"))
Output
Raghu
Not assigned
Access Nested JSON Objects in Python
You can access inner nodes in the same way as that you access elements in multi-dimensional array.
In this example, we take a JSON string, in which one of the element marks has elements in it {"science":87, "maths":34}.
Python Program
import json
#json string
jsonStr = '{"rollno":25, "name":"Raghu", "marks":{"science":87, "maths":34}}'
#parse/load json string into json object
jsonObj = json.loads(jsonStr)
#access inner nodes
print(jsonObj["marks"]["science"])
Output
87
After parsing, the outer JSON object becomes a Python dictionary, and the value of marks becomes another dictionary. Chained keys can therefore be used to reach the nested value.
Parse a JSON Array in Python
You can parse a JSON array and access the elements using index. The index starts from 0 and increments for the subsequent elements as in a list.
In the following example, we have an array of two elements. We shall parse the JSON array using the same loads() function, and then access the array elements using index.
Python Program
import json
#json string
jsonStr = '[{"rollno":1, "name":"Prasanth"}, {"rollno":2, "name":"Raghu"}]'
#parse/load json string into json object
jsonObj = json.loads(jsonStr)
#access the json array
print(jsonObj[0])
print(jsonObj[1])
Output
{'rollno': 1, 'name': 'Prasanth'}
{'rollno': 2, 'name': 'Raghu'}
The decoded value is a Python list containing dictionaries. You can loop through the list to process every JSON object.
import json
json_text = '[{"rollno": 1, "name": "Prasanth"}, {"rollno": 2, "name": "Raghu"}]'
students = json.loads(json_text)
for student in students:
print(student["rollno"], student["name"])
Output
1 Prasanth
2 Raghu
Read JSON Data from a File with json.load()
Use json.load() to decode JSON directly from an open file. Consider a file named student.json with the following content.
{
"rollno": 25,
"name": "Raghu",
"subjects": ["Science", "Mathematics"]
}
Open the file using UTF-8 encoding and pass the file object to json.load().
import json
with open("student.json", "r", encoding="utf-8") as file:
student = json.load(file)
print(student["name"])
print(student["subjects"][0])
Output
Raghu
Science
The with statement closes the file automatically after the block finishes, including when an exception occurs.
Convert Python Objects to JSON
You can convert some of the types of Python Objects to JSON. Using this, you can save python objects directly to files in persistent storage. Or you can transmit them to other applications as JSON string, which is a good thing, because most of the applications are embracing JSON syntax for data transfer between the applications.
We can convert following Python objects to JSON String.
- Dictionary
- List
- Tuple
- String
- Integer
- Float
- Boolean
- None
In the following example, we shall convert some of the Python objects to JSON String.
Python Program
import json
#list to json string
alist = [12, 57, 41, 68, 47, 62]
jsonList = json.dumps(alist)
print(jsonList)
#tuple to json string
atuple = (12, "Raghu")
jsonTuple = json.dumps(atuple)
print(jsonTuple)
#dictionary to json string
aDict = {"rollno":12, "name":"Raghu"}
jsonDict = json.dumps(aDict)
print(jsonDict)
#string to json
str = "Hello World"
jsonStr = json.dumps(str)
print(jsonStr)
#int to json
i = 25
jsonInt = json.dumps(i)
print(jsonInt)
#float to json
f = 25.256
jsonFloat = json.dumps(f)
print(jsonFloat)
#boolean to json
bool = True
jsonBool = json.dumps(bool)
print(jsonBool)
#null to json
a = None
jsonNone = json.dumps(a)
print(jsonNone)
Output
[12, 57, 41, 68, 47, 62]
[12, "Raghu"]
{"rollno": 12, "name": "Raghu"}
"Hello World"
25
25.256
true
null
A Python tuple is encoded as a JSON array. When that JSON is decoded again, it becomes a Python list because JSON does not have a separate tuple type.
Write Python Data to a JSON File
Use json.dump() to write a Python object directly to a file. The following example writes a dictionary to student.json.
import json
student = {
"rollno": 25,
"name": "Raghu",
"subjects": ["Science", "Mathematics"]
}
with open("student.json", "w", encoding="utf-8") as file:
json.dump(student, file, indent=2)
The file contains:
{
"rollno": 25,
"name": "Raghu",
"subjects": [
"Science",
"Mathematics"
]
}
Opening a file with mode "w" replaces its existing content. Use an appropriate storage strategy when multiple records must be preserved instead of repeatedly overwriting one JSON document.
Format JSON Output with indent and sort_keys
By default, json.dumps() produces compact JSON. Use indent to make nested data easier to read and sort_keys=True to sort object keys alphabetically.
import json
student = {
"name": "Raghu",
"rollno": 25,
"marks": {
"science": 87,
"mathematics": 91
}
}
formatted = json.dumps(student, indent=2, sort_keys=True)
print(formatted)
Output
{
"marks": {
"mathematics": 91,
"science": 87
},
"name": "Raghu",
"rollno": 25
}
For compact JSON, the separators argument can remove optional spaces.
import json
data = {"name": "Raghu", "class": 7}
compact = json.dumps(data, separators=(",", ":"))
print(compact)
Output
{"name":"Raghu","class":7}
Preserve Unicode Characters in Python JSON
Python escapes non-ASCII characters by default when encoding JSON. Set ensure_ascii=False to keep readable Unicode characters in the resulting string or file.
import json
data = {
"greeting": "नमस्ते",
"city": "München"
}
print(json.dumps(data, ensure_ascii=False))
Output
{"greeting": "नमस्ते", "city": "München"}
When writing this output to a file, open the file with encoding="utf-8".
Handle Invalid JSON with JSONDecodeError
Invalid JSON passed to json.loads() or json.load() raises json.JSONDecodeError. Common causes include single-quoted strings, trailing commas, missing commas, and unquoted object keys.
import json
json_text = '{"name": "Raghu", "class": 7,}'
try:
student = json.loads(json_text)
except json.JSONDecodeError as error:
print("Invalid JSON")
print("Line:", error.lineno)
print("Column:", error.colno)
print("Message:", error.msg)
The trailing comma makes the string invalid JSON. The exception includes the line, column, and character position at which decoding failed.
JSON Requires Double Quotes
JSON strings and object keys must use double quotes. The following is a valid Python dictionary but not valid JSON text:
{'name': 'Raghu'}
Valid JSON uses double quotes:
{"name": "Raghu"}
Serialize Python datetime and Other Custom Objects
The standard JSON encoder cannot directly serialize every Python type. Objects such as datetime, date, Decimal, and custom class instances require conversion to a supported value first.
The default argument can provide a conversion function. This example converts a datetime object to an ISO 8601 string.
import json
from datetime import datetime, timezone
record = {
"event": "login",
"created_at": datetime(2026, 7, 27, 9, 30, tzinfo=timezone.utc)
}
json_text = json.dumps(
record,
default=lambda value: value.isoformat()
)
print(json_text)
Output
{"event": "login", "created_at": "2026-07-27T09:30:00+00:00"}
A named function is preferable when different unsupported types need separate handling.
import json
from datetime import date, datetime
from decimal import Decimal
def encode_value(value):
if isinstance(value, (date, datetime)):
return value.isoformat()
if isinstance(value, Decimal):
return str(value)
raise TypeError(f"Object of type {type(value).__name__} is not JSON serializable")
record = {
"date": date(2026, 7, 27),
"amount": Decimal("19.95")
}
print(json.dumps(record, default=encode_value))
Output
{"date": "2026-07-27", "amount": "19.95"}
Decode JSON Numbers with Decimal Precision
JSON decimal numbers are normally decoded as Python float values. For applications that require decimal arithmetic without binary floating-point approximation, pass Decimal through parse_float.
import json
from decimal import Decimal
json_text = '{"amount": 19.95}'
data = json.loads(json_text, parse_float=Decimal)
print(data["amount"])
print(type(data["amount"]))
Output
19.95
<class 'decimal.Decimal'>
Validate JSON Syntax from the Command Line
Python’s JSON module includes a command-line tool that can validate and format a JSON file.
python -m json.tool student.json
Valid JSON is printed in an indented form. Invalid JSON produces an error identifying where parsing failed.
Python json.load() vs loads() and dump() vs dumps()
The function names differ by whether the operation uses a string or a file-like object.
| Function | Input or output | Purpose |
|---|---|---|
json.loads() | JSON string input | Decode a string into a Python object |
json.load() | Open file or file-like input | Read and decode JSON from a stream |
json.dumps() | JSON string output | Encode a Python object as a string |
json.dump() | Open file or file-like output | Encode and write JSON to a stream |
The letter s in loads and dumps can be remembered as referring to a string.
Python JSON Usage Guidelines
- Open JSON text files with UTF-8 encoding.
- Use
json.load()for files andjson.loads()for strings. - Catch
JSONDecodeErrorwhen JSON comes from an external or untrusted source. - Use
dict.get()or explicit validation for optional keys. - Do not assume that decoded JSON has the expected structure or data types.
- Use
indentfor human-readable files and compact separators when smaller output is required. - Convert unsupported types such as
datetimeexplicitly instead of relying on implicit behavior. - Remember that JSON parsing does not make untrusted content safe for use in SQL queries, shell commands, or HTML output.
Python JSON Frequently Asked Questions
How do I convert a JSON string to a Python dictionary?
Pass the JSON string to json.loads(). When the top-level JSON value is an object, the returned value is a Python dictionary.
How do I convert a Python dictionary to JSON?
Use json.dumps(dictionary) to create a JSON string, or json.dump(dictionary, file) to write it directly to an open file.
Why does json.dumps() fail for datetime objects?
JSON has no native date-time type, so the default encoder does not know how to represent a Python datetime. Convert it to a string, commonly with isoformat(), or provide a function through the default argument.
What is the difference between JSON null and Python None?
They represent corresponding null values in the two formats. Decoding JSON converts null to None, while encoding Python converts None to null.
Can JSON contain comments or trailing commas?
Standard JSON does not allow comments or trailing commas. Python’s built-in json decoder rejects them with JSONDecodeError.
Python JSON Tutorial Summary
In this Python Tutorial, we learned how to parse JSON strings and files, access objects and arrays, convert Python values to JSON, write JSON files, format and validate JSON, preserve Unicode text, handle invalid input, and serialize types that the standard encoder does not support directly.
TutorialKart.com