Python JSON
Python JSON
JSON stands for JavaScript Object Notation.
It is a lightweight data format used for storing and transporting data โ commonly used in APIs.
Python provides a built-in module named json to work with JSON data.
โ JSON in Python vs Python Dictionary
| JSON Data Type | Python Equivalent |
|---|---|
Object {} |
dict |
Array [] |
list |
| String | str |
| Number | int/float |
| Boolean | True/False |
| Null | None |
๐ Converting Python to JSON โ json.dumps()
dumps() means Dump as String.
Example:
โถ๏ธ Output:
๐จ Formatting JSON Output
Additional formatting options:
| Argument | Meaning |
|---|---|
indent |
Pretty formatting |
sort_keys=True |
Sorts keys alphabetically |
separators=(",", ": ") |
Controls spacing |
Example:
๐ Converting JSON to Python โ json.loads()
loads() means Load from String.
๐ Working with JSON Files
๐ Write JSON to File โ json.dump()
๐ฅ Read JSON from File โ json.load()
๐ JSON with Lists
๐งช Converting Python Objects
Python can serialize only basic types.
To convert custom objects, we use:
Option 1 โ Convert manually
Option 2 โ Using default Parameter
โ ๏ธ Errors to Avoid
โ JSON strings must use double quotes ", not '.
๐ฏ Summary Table
| Action | Function |
|---|---|
| Python โก JSON (string) | json.dumps() |
| JSON โก Python (string) | json.loads() |
| Write JSON to file | json.dump() |
| Read JSON from file | json.load() |
