JSON in Python

Why JSON in Python?

Python is one of the most popular programming languages for data processing, automation, web development, and machine learning. JSON is used constantly in Python projects — to communicate with REST APIs, to store configuration data, to save and load records, and to process data from the web.

Python has a built-in module called json that handles everything needed to work with JSON. No external library needs to be installed — it is available as part of Python's standard library.

Importing the json Module

Before using JSON in Python, the json module must be imported at the top of the script:

import json

Key Methods in Python's json Module

MethodPurposeWorks With
json.loads()Parse a JSON string → Python dictionaryString in memory
json.dumps()Convert Python object → JSON stringString in memory
json.load()Read a JSON file → Python dictionaryFile object
json.dump()Write Python object → JSON fileFile object

A simple memory trick: methods with an s at the end (loads, dumps) work with strings. Methods without the s (load, dump) work with files.

1. Parsing a JSON String — json.loads()

json.loads() converts a JSON-formatted string into a Python dictionary (or list, depending on the JSON structure).

import json

json_string = '{"name": "Pallavi Singh", "age": 26, "city": "Bhopal"}'

person = json.loads(json_string)

print(person["name"])   # Output: Pallavi Singh
print(person["age"])    # Output: 26
print(type(person))     # Output: <class 'dict'>

2. Converting Python Object to JSON String — json.dumps()

json.dumps() converts a Python dictionary or list into a JSON-formatted string.

import json

employee = {
    "name": "Govindan Nair",
    "department": "IT",
    "salary": 48000,
    "isActive": True
}

json_string = json.dumps(employee)

print(json_string)
# Output: {"name": "Govindan Nair", "department": "IT", "salary": 48000, "isActive": true}

Notice that Python's True becomes true (lowercase) in JSON, as required by the JSON standard.

Pretty-Printing with json.dumps()

Pass the indent parameter to produce readable, formatted JSON:

pretty = json.dumps(employee, indent=2)
print(pretty)

Output:

{
  "name": "Govindan Nair",
  "department": "IT",
  "salary": 48000,
  "isActive": true
}

3. Reading a JSON File — json.load()

json.load() reads a JSON file and returns the data as a Python object.

File: student.json

{
  "name": "Dhruv Mathur",
  "rollNo": 312,
  "subjects": ["Physics", "Chemistry", "Maths"],
  "passed": true
}

Python Script:

import json

with open("student.json", "r") as file:
    student = json.load(file)

print(student["name"])          # Output: Dhruv Mathur
print(student["subjects"][0])   # Output: Physics
print(student["passed"])        # Output: True

Using with open() is the recommended way to open files in Python — it automatically closes the file when done.

4. Writing to a JSON File — json.dump()

json.dump() writes a Python object to a JSON file.

import json

product = {
    "productId": "PRD-991",
    "name": "Study Lamp",
    "price": 850,
    "inStock": True
}

with open("product.json", "w") as file:
    json.dump(product, file, indent=2)

print("product.json has been created.")

Python to JSON — Data Type Mapping

When converting from Python to JSON, data types are automatically mapped as follows:

Python TypeJSON Equivalent
dictObject { }
listArray [ ]
tupleArray [ ]
strString
intNumber
floatNumber
Truetrue
Falsefalse
Nonenull

Working with JSON Arrays in Python

import json

json_array = '[{"name": "Akash", "score": 85}, {"name": "Nidhi", "score": 92}]'

students = json.loads(json_array)

for student in students:
    print(student["name"] + ": " + str(student["score"]))

# Output:
# Akash: 85
# Nidhi: 92

Fetching JSON from an API in Python

Python's requests library (needs to be installed with pip install requests) makes it easy to fetch JSON from web APIs:

import requests

response = requests.get("https://jsonplaceholder.typicode.com/users/1")
user = response.json()  # Automatically parses JSON

print(user["name"])              # Output: Leanne Graham
print(user["address"]["city"])   # Output: Gwenborough

The .json() method on the response object automatically calls json.loads() internally — no manual parsing is needed.

Handling Errors When Parsing JSON in Python

import json

bad_json = '{"name": "Raj", "age": }'  # Invalid JSON

try:
    data = json.loads(bad_json)
except json.JSONDecodeError as e:
    print("JSON parsing error: " + str(e))

Key Points to Remember

  • Python's built-in json module handles all JSON operations
  • json.loads() — JSON string to Python dict (memory)
  • json.dumps() — Python dict to JSON string (memory)
  • json.load() — read JSON from a file
  • json.dump() — write JSON to a file
  • Python's True/False/None become true/false/null in JSON automatically
  • Always use try...except json.JSONDecodeError when parsing untrusted data

Summary

Working with JSON in Python is clean and straightforward thanks to the built-in json module. The four core methods — loads, dumps, load, and dump — cover every common use case. From reading API responses to saving data to files, JSON is the most common data format Python developers work with in real-world projects.

Leave a Comment

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