JSON stands for Javascript Object Notation.
It is a lightweight format used for storing and transferring data.
Python has a built-in package called json, which can be used to work with JSON data.
Data Conversion :
| JSON | Python |
|---|---|
| object | dict |
| array | list |
| string | str |
| number | int / float |
| true | True |
| false | False |
| null | None |
Converting Python Object -> JSON :
json.dumps( ) converts python data into JSON String.
Python
import json student = { "name": "Rahul", "age": 22, "is_student": True } json_data = json.dumps(student) print(json_data) #output {"name": "Rahul", "age": 22, "is_student": true}Converting JSON -> Python Object :
json.loads( ) converts JSON string into Python object.
Python
data = '{"name": "Rahul", "age": 22}' student = json.loads(data) print(student) print(type(student)) #output {'name': 'Rahul', 'age': 22} <class 'dict'> Reading JSON from a File :
Python
import json with open("data.json") as file: data = json.load(file) print(data)Writing JSON to a File :
Python
import json student = { "name": "Rahul", "age": 22, "city": "Chennai" } with open("student.json", "w") as file: json.dump(student, file, indent=4) | Function | Purpose |
|---|---|
| json.dumps() | Convert Python → JSON string |
| json.loads() | Convert JSON string → Python |
| json.dump() | Write JSON to file |
| json.load() | Read JSON from file |