PythonFile HandlingJSON File Handling

JSON File Handling in Python

JSON (JavaScript Object Notation) is a lightweight data format often used for data exchange between systems. Python’s json module provides tools to handle JSON files effectively.


Introduction to JSON Files

What is JSON?

JSON represents data as key-value pairs, arrays, and nested objects. It is human-readable and widely used in web development, APIs, and configuration files.

Example JSON Content

{
  "name": "Alice",
  "age": 25,
  "city": "New York",
  "skills": ["Python", "Data Analysis", "Machine Learning"]
}

Using Python’s json Module

The json module in Python allows for reading and writing JSON data easily.

Importing the Module

import json

Reading JSON Files

Loading JSON from a String

Use json.loads() to parse a JSON string into a Python dictionary.

import json
 
data = '{"name": "Alice", "age": 25, "city": "New York"}'
parsed_data = json.loads(data)
print(parsed_data["name"])  # Output: Alice

Reading JSON from a File

Use json.load() to read JSON data from a file.

import json
 
with open("data.json", "r") as file:
    data = json.load(file)
    print(data["skills"])  # Output: ['Python', 'Data Analysis', 'Machine Learning']

Writing JSON Files

Writing JSON to a String

Use json.dumps() to convert a Python dictionary to a JSON string.

import json
 
data = {"name": "Alice", "age": 25, "city": "New York"}
json_string = json.dumps(data)
print(json_string)

Writing JSON to a File

Use json.dump() to write JSON data to a file.

import json
 
data = {
    "name": "Alice",
    "age": 25,
    "city": "New York",
    "skills": ["Python", "Data Analysis", "Machine Learning"]
}
 
with open("output.json", "w") as file:
    json.dump(data, file, indent=4)

This creates an output.json file with formatted content:

{
    "name": "Alice",
    "age": 25,
    "city": "New York",
    "skills": [
        "Python",
        "Data Analysis",
        "Machine Learning"
    ]
}

Practical Use Cases

  1. Data Exchange: Transfer structured data between systems or applications.
  2. Configuration Files: Store application settings in a JSON file.
  3. APIs: Work with JSON data returned from APIs.

Try It Yourself

Problem 1: Read Nested JSON Data

Write a program to extract the “skills” from a nested JSON file.

Show Solution
import json
 
with open("data.json", "r") as file:
    data = json.load(file)
    print("Skills:", data["skills"])

Problem 2: Add a New Key-Value Pair and Save

Write a program to add a “hobbies” key to a JSON object and save it to a file.

Show Solution
import json
 
with open("data.json", "r") as file:
    data = json.load(file)
 
data["hobbies"] = ["Reading", "Traveling"]
 
with open("data_with_hobbies.json", "w") as file:
    json.dump(data, file, indent=4)

JSON file handling is an essential skill for modern Python developers. Understanding how to read, write, and manipulate JSON will empower you to work efficiently with APIs and other structured data sources.


Pyground

Play with Python!

Output: