Python JSON
JSON (JavaScript Object Notation) is a lightweight format used to store and exchange data.
It is text-based, easy to read, and widely used in APIs, configuration files, and web applications.
Working with JSON in Python
Python includes a built-in module named json that allows you to easily
read, write, and manipulate JSON data.
Importing the JSON Module
import json
Parsing JSON (JSON → Python)
When you receive data in JSON format, it is usually a string.
To convert this JSON string into a Python object, use the json.loads()
method.
Example: Convert JSON String to Python Dictionary
Output:
After parsing, the JSON data becomes a Python dictionary, which you can access using keys.
Converting Python to JSON (Python → JSON)
To convert a Python object into a JSON string, use the json.dumps()
method.
Example: Convert Python Dictionary to JSON
Output:
The output is a JSON-formatted string, ready to be stored or sent over a network.
Supported Python Data Types
The following Python data types can be converted into JSON:
• dict
• list
• tuple
• str
• int
• float
• True
• False
• None
Example: Convert Multiple Python Types to JSON
Output:
["HTML", "CSS", "JavaScript"]
["Red", "Green", "Blue"]
"Welcome"
99
45.6
true
false
null
Python to JSON Type Conversion Table
| Python Type | JSON Type |
|---|---|
dict | Object |
list | Array |
tuple | Array |
str | String |
int | Number |
float | Number |
True | true |
False | false |
None | null |
Complex Python Object to JSON
Python dictionaries can contain nested data such as lists, tuples, and other dictionaries.
Example: Convert Complex Data Structure
Output:
Formatting JSON Output
Raw JSON strings are difficult to read.
The json.dumps() method provides parameters to format the output.
Using Indentation
The indent parameter adds line breaks and indentation for better readability.
Output:
"student": "Amit",
"age": 21,
"is_graduated": false
}
Custom Separators
You can customize how keys and values are separated.
Output:
"student" => "Amit" |
"age" => 21 |
"is_graduated" => false
}
Sorting JSON Keys
To display JSON keys in alphabetical order, use the sort_keys parameter.
Output:
"age": 21,
"is_graduated": false,
"student": "Amit"
}
