JSON (JavaScript Object Notation) is a lightweight format used for storing and exchanging data. Python provides a built-in json module to work with JSON data.
Importing the JSON Module
Example
import json
Convert Python Dictionary to JSON
The dumps() method converts a Python object into a JSON string.
Syntax
json.dumps(object)
Example
import json
student = {
"name": "John",
"age": 20
}
result = json.dumps(student)
print(result)
Output:
{"name": "John", "age": 20}
Convert JSON to Python Dictionary
The loads() method converts a JSON string into a Python object.
Syntax
json.loads(json_string)
Example
import json
data = '{"name":"John","age":20}'
result = json.loads(data)
print(result)
Output:
{'name': 'John', 'age': 20}
Access JSON Data
Example
import json
data = '{"name":"John","age":20}'
student = json.loads(data)
print(student["name"])
Output:
John
Write JSON to a File
The dump() method writes JSON data to a file.
Example
import json
student = {
"name": "John",
"age": 20
}
with open("student.json", "w") as file:
json.dump(student, file)
Read JSON from a File
The load() method reads JSON data from a file.
Example
import json
with open("student.json", "r") as file:
data = json.load(file)
print(data)
Output:
{'name': 'John', 'age': 20}
Format JSON Output
Use the indent parameter to make JSON more readable.
Example
import json
student = {
"name": "John",
"age": 20
}
print(json.dumps(student, indent=4))
Output:
{
"name": "John",
"age": 20
}
Convert Python List to JSON
Example
import json
fruits = ["apple", "banana", "mango"]
print(json.dumps(fruits))
Output:
["apple", "banana", "mango"]
Summary
- JSON is used for data storage and data exchange.
- The
jsonmodule is built into Python. dumps()converts Python objects to JSON strings.loads()converts JSON strings to Python objects.dump()writes JSON data to a file.load()reads JSON data from a file.- The
indentparameter formats JSON output for readability.