JSON (JavaScript Object Notation) is a lightweight data format used for storing and transferring data. It is widely used in web development for API responses and configurations because it is easy to read and write.
Python provides the json
module to work with JSON data.
1. What is JSON?
- JSON represents data as key-value pairs.
- It supports simple data types such as:
- Strings
- Numbers
- Booleans (
true
/false
) - Arrays (equivalent to Python lists)
- Objects (equivalent to Python dictionaries)
- Null (
null
in JSON, equivalent toNone
in Python)
Example of JSON Data:
{
"name": "Junaid Shaikh",
"age": 29,
"isStudent": false,
"skills": ["Python", "JavaScript", "SQL"],
"address": {
"city": "Manmad",
"zip": "423104"
}
}
2. Python’sjson
Module
The json
module allows you to:
- Convert JSON strings to Python objects (parsing).
- Convert Python objects to JSON strings (serialization).
Importing the JSON Module
import json
3. Parsing JSON (Converting JSON to Python)
To parse JSON data (convert JSON string to a Python object), use json.loads()
.
import json
# JSON string
json_data = '{"name": "Junaid", "age": 29, "isStudent": false}'
# Convert JSON string to Python dictionary
python_obj = json.loads(json_data)
print(python_obj) # Outputs: {'name': 'Junaid', 'age': 29, 'isStudent': False}
print(python_obj['name']) # Outputs: Junaid
Key Points:
- JSON objects are converted to Python dictionaries.
- JSON arrays are converted to Python lists.
true
,false
, andnull
in JSON are converted toTrue
,False
, andNone
in Python.
4. Serializing JSON (Converting Python to JSON)
To convert a Python object to a JSON string, use json.dumps()
.
# Python object
python_obj = {
"name": "Arsheen",
"age": 24,
"isStudent": True,
"skills": ["Python", "Machine Learning"]
}
# Convert Python dictionary to JSON string
json_data = json.dumps(python_obj)
print(json_data) # Outputs: {"name": "Arsheen", "age": 24, "isStudent": true, "skills": ["Python", "Machine Learning"]}
Key Points:
- Python dictionaries are converted to JSON objects.
- Python lists are converted to JSON arrays.
True
,False
, andNone
in Python are converted totrue
,false
, andnull
in JSON.
5. Formatting JSON Output
5.1 Pretty Printing
You can make JSON output more readable using the indent
parameter in json.dumps()
.
python_obj = {
"name": "Aadil",
"age": 27,
"skills": ["Python", "Django", "React"]
}
# Pretty print JSON string
json_data = json.dumps(python_obj, indent=4)
print(json_data)
Output
{
"name": "Aadil",
"age": 27,
"skills": [
"Python",
"Django",
"React"
]
}
5.2 Sorting Keys
You can sort keys in JSON output using the sort_keys
parameter.
Example:
data = {"b": 1, "a": 2, "c": 3}
# Convert to JSON string with sorted keys
json_data = json.dumps(data, sort_keys=True, indent=4)
print(json_data)
Output:
{
"a": 2,
"b": 1,
"c": 3
}
JSON and Python make data exchange between systems simple and efficient. Understanding JSON is essential for working with APIs and modern data-driven applications!