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.

import json

โœ… 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:

import json

data = {
“name”: “John”,
“age”: 25,
“city”: “New York”
}

json_string = json.dumps(data)
print(json_string)

โ–ถ๏ธ Output:

{"name": "John", "age": 25, "city": "New York"}

๐ŸŽจ Formatting JSON Output

print(json.dumps(data, indent=4))

Additional formatting options:

Argument Meaning
indent Pretty formatting
sort_keys=True Sorts keys alphabetically
separators=(",", ": ") Controls spacing

Example:

print(json.dumps(data, indent=4, sort_keys=True))

๐Ÿ”„ Converting JSON to Python โ€” json.loads()

loads() means Load from String.

json_data = '{"name": "John", "age": 25, "city": "New York"}'

python_dict = json.loads(json_data)
print(python_dict)
print(type(python_dict))


๐Ÿ“ Working with JSON Files

๐Ÿ“ Write JSON to File โ€” json.dump()

data = {"name": "Alice", "age": 30, "city": "London"}

with open(“data.json”, “w”) as file:
json.dump(data, file, indent=4)


๐Ÿ“ฅ Read JSON from File โ€” json.load()

with open("data.json", "r") as file:
result = json.load(file)
print(result)

๐Ÿš€ JSON with Lists

people_json = '''
[
{"name": "John", "age": 25},
{"name": "Emma", "age": 28}
]
'''
people = json.loads(people_json)
print(people[1][“name”])

๐Ÿงช Converting Python Objects

Python can serialize only basic types.
To convert custom objects, we use:

Option 1 โ€” Convert manually

class Student:
def __init__(self, name, roll):
self.name = name
self.roll = roll
student = Student(“Raj”, 101)json_data = json.dumps(student.__dict__)
print(json_data)

Option 2 โ€” Using default Parameter

def encode_student(o):
return o.__dict__
json_data = json.dumps(student, default=encode_student)
print(json_data)

โš ๏ธ Errors to Avoid

โŒ JSON strings must use double quotes ", not '.

wrong = "{'name': 'John'}" # invalid JSON
correct = '{"name": "John"}'

๐ŸŽฏ 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()

๐Ÿงน Mini Practical Example

import json

student = {
“name”: “Amit”,
“marks”: [85, 90, 92],
“passed”: True
}

# Save to file
with open(“student.json”, “w”) as f:
json.dump(student, f, indent=4)

# Read from file
with open(“student.json”, “r”) as f:
data = json.load(f)

print(data)

CodeCapsule

Sanjit Sinha โ€” Web Developer | PHP โ€ข Laravel โ€ข CodeIgniter โ€ข MySQL โ€ข Bootstrap Founder, CodeCapsule โ€” Student projects & practical coding guides. Email: info@codecapsule.in โ€ข Website: CodeCapsule.in

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *