- Home
- /
- Python JSON
Python Tutorial
Introduction
Python Data Types & Oper...
Python Strings
Python Lists
Python Tuples
Python Sets
Python Dictionaries
Conditional Statements
Python Loops
Python Functions
Python Modules
Python OOPS
Advanced Topics
File Handling
- Home
- /
- Python JSON
Python JSON
JSON stands for JavaScript Object Notation — a lightweight format to store and share data. Python provides a built-in json
module that lets you easily work with JSON data.
A. Convert JSON String to Python Object
Let’s say we receive a JSON-formatted string (maybe from a web server). We can convert that string into a regular Python object using json.loads()
.
import json
json_data = '["Apple", "Banana", "Cherry"]'
fruits = json.loads(json_data)
print(fruits)
Output:
['Apple', 'Banana', 'Cherry']
JSON list becomes a Python list.
B. Convert Python Object to JSON String
If we want to store or send data, we can convert a Python object into a JSON string using json.dumps()
.
import json
colors = ['Cyan', 'Magenta', 'Yellow', 'Black']
json_string = json.dumps(colors)
print(json_string)
Output:
["Cyan", "Magenta", "Yellow", "Black"]
Python list becomes a JSON-formatted string.
C. Type Conversion: Python to JSON
Python and JSON have different names for similar types. When converting, Python types are automatically mapped to equivalent JSON types.
import json
print(json.dumps(10)) # int
print(json.dumps(3.14)) # float
print(json.dumps("Learn")) # str
print(json.dumps(True)) # bool
print(json.dumps(False)) # bool
print(json.dumps(None)) # NoneType
Output:
10
3.14
"Learn"
true
false
null
Notice how True
becomes true
, None
becomes null
, and strings are always in double quotes.
Summary
Use
json.loads()
to convert a JSON string into a Python object.Use
json.dumps()
to convert Python data into a JSON string.Python and JSON types are automatically mapped during conversion.
This is especially useful in APIs, file storage, or any time you need to exchange structured data.