Your Search Bar For Shrewd Tips

How To Clean Json File In Python


JSON files are easy to share between applications, but they can become difficult to work with when they contain inconsistent formatting, extra whitespace, duplicate records, unexpected values, or invalid syntax. Python’s built-in json module makes it straightforward to read, inspect, clean, validate, and rewrite JSON data without installing an extra package.

In this guide, you’ll learn how to clean a JSON file in Python safely. You’ll see how to format JSON consistently, normalize values, remove unwanted records, handle common errors, and save the cleaned data without accidentally losing the original file.

What Does It Mean to Clean a JSON File?

Cleaning a JSON file means making its data more consistent or useful while keeping the file valid JSON. The right cleanup depends on your data and your application. One file may only need consistent indentation, while another may need blank strings removed, whitespace normalized, or invalid records filtered out.

Common JSON cleanup tasks include:

  • Reformatting JSON with consistent indentation.
  • Removing unnecessary whitespace from string values.
  • Normalizing text, such as converting names to lowercase.
  • Removing empty records or records missing required fields.
  • Checking that the file contains valid JSON and the expected data structure.
  • Writing the cleaned result to a new file.

Before changing a file, decide what “clean” means for your project. Removing a blank field may be helpful in one application but harmful in another. A reliable cleanup script should follow clear rules rather than silently changing data.

Read and Reformat JSON with Python

Python includes the json module, which can parse JSON into Python objects and serialize those objects back into JSON. JSON objects become dictionaries, JSON arrays become lists, and JSON values such as strings, numbers, booleans, and null become their Python equivalents.

The following example reads a JSON file and writes a consistently formatted copy:

import json
from pathlib import Path

input_path = Path("data.json")
output_path = Path("data_cleaned.json")

with input_path.open("r", encoding="utf-8") as file:
    data = json.load(file)

with output_path.open("w", encoding="utf-8") as file:
    json.dump(data, file, indent=2, ensure_ascii=False)
    file.write("\n")

The indent=2 option makes the output easier to read. Setting ensure_ascii=False keeps Unicode characters, such as accented letters, readable rather than converting them into escape sequences. The final newline is a useful convention for text files and makes command-line diffs cleaner.

Reformatting does not change the meaning of valid JSON data. It does, however, give you a consistently formatted output file. Writing to a separate path also preserves the source file while you review the result.

Handle Invalid JSON Safely

json.load() raises a json.JSONDecodeError when the file is not valid JSON. For example, a missing comma, an extra trailing comma, or a string with unescaped quotation marks can prevent the file from being parsed. JSON also requires double quotes around property names and strings; single quotes are not valid JSON syntax.

Catch parsing errors so your script can report the problem clearly instead of stopping with a confusing traceback:

import json

try:
    with open("data.json", "r", encoding="utf-8") as file:
        data = json.load(file)
except json.JSONDecodeError as error:
    print(f"Invalid JSON: {error}")
    print(f"Line {error.lineno}, column {error.colno}")
    raise

The error includes a line and column, which can help you locate the malformed part of the file. Python’s standard JSON parser expects strict JSON; it does not automatically repair broken syntax. Avoid broad find-and-replace “fixes” unless you understand the file format, because they can alter valid values as well as mistakes.

If the file is important, keep the original unchanged and write any corrected or cleaned version to a separate output file. For recurring data-quality problems, it is usually better to fix the system that generates the JSON than to rely on fragile repair rules.

Clean String Values Recursively

JSON data can contain strings at many levels: at the top level, inside objects, and inside arrays. A recursive function can clean string values throughout a nested structure. The example below trims leading and trailing whitespace while leaving keys and non-string values unchanged.

def clean_strings(value):
    if isinstance(value, dict):
        return {
            key: clean_strings(item)
            for key, item in value.items()
        }

    if isinstance(value, list):
        return [clean_strings(item) for item in value]

    if isinstance(value, str):
        return value.strip()

    return value

Use the function after loading the JSON and before saving it:

data = clean_strings(data)

with open("data_cleaned.json", "w", encoding="utf-8") as file:
    json.dump(data, file, indent=2, ensure_ascii=False)
    file.write("\n")

This function preserves empty strings. If your requirements say that blank strings should become None, you could change the string branch to return value.strip() or None. When serialized as JSON, Python’s None becomes JSON null. Only make that change when downstream applications accept null values in those fields.

You can also apply field-specific rules, such as lowercasing an email address or trimming a particular description field. Field-specific cleanup is often safer than changing every string, especially when capitalization or spacing has meaning in your data.

Remove Empty or Invalid Records

Many JSON files contain an array of records, such as a list of users, products, or events. You can filter that list with a Python list comprehension. First, check that the loaded data is actually a list, then define which records are acceptable.

if not isinstance(data, list):
    raise ValueError("Expected the JSON file to contain a list")

cleaned_records = [
    record
    for record in data
    if isinstance(record, dict)
    and record.get("id") is not None
]

This example keeps dictionary records that contain a non-null id. It does not assume that every record needs the same cleanup rules. For example, you might also require a nonblank name or a valid email address:

def is_valid_record(record):
    return (
        isinstance(record, dict)
        and record.get("id") is not None
        and isinstance(record.get("name"), str)
        and record["name"].strip() != ""
    )

cleaned_records = [record for record in data if is_valid_record(record)]

Be careful when removing records. Save a count of the records before and after filtering, and consider logging rejected entries so you can investigate why they failed. Deleting data without recording the reason can make it difficult to detect a problem in the source system.

Normalize Values and Remove Duplicates

Normalization makes comparable values follow the same convention. For example, if a field is intended to store a category label, converting it to lowercase and trimming whitespace can prevent values such as " News " and "news" from being treated as different categories.

for record in cleaned_records:
    category = record.get("category")
    if isinstance(category, str):
        record["category"] = category.strip().lower()

To remove duplicate records, choose a stable key that identifies a record, such as an ID. The following example keeps the first record for each ID:

unique_records = []
seen_ids = set()

for record in cleaned_records:
    record_id = record["id"]
    if record_id not in seen_ids:
        seen_ids.add(record_id)
        unique_records.append(record)

This approach assumes that IDs are hashable and that the first occurrence should be kept. If the newest record should take priority, or duplicates should be merged, implement that rule explicitly. Do not remove records merely because their JSON text looks similar; two records with different IDs or meaningful differences may both be needed.

Validate the Data Before Saving

A file can be syntactically valid JSON and still contain the wrong data. For instance, your program may expect a list of objects but receive a dictionary, or a required field may be missing. Validate the structure and important values after parsing and cleanup.

if not isinstance(data, list):
    raise ValueError("Expected a list of records")

for index, record in enumerate(data):
    if not isinstance(record, dict):
        raise ValueError(f"Record {index} must be an object")
    if "id" not in record:
        raise ValueError(f"Record {index} is missing an id")

For more complex projects, a validation library or a JSON Schema can describe required fields, allowed types, and value constraints. Regardless of the method, validation helps catch errors before cleaned data reaches another application.

Save the Cleaned JSON File Safely

Once the data is clean and validated, serialize it to a destination file. Keeping the input and output paths separate is the simplest way to avoid overwriting your only copy of the original data.

import json
from pathlib import Path

output_path = Path("data_cleaned.json")

with output_path.open("w", encoding="utf-8") as file:
    json.dump(cleaned_records, file, indent=2, ensure_ascii=False)
    file.write("\n")

For an important file, you can write to a temporary file first and then replace the destination after the write succeeds. This reduces the chance of leaving a partially written output if the script is interrupted.

import json
import os
from pathlib import Path

output_path = Path("data_cleaned.json")
temporary_path = output_path.with_suffix(".tmp")

with temporary_path.open("w", encoding="utf-8") as file:
    json.dump(cleaned_records, file, indent=2, ensure_ascii=False)
    file.write("\n")

os.replace(temporary_path, output_path)

Use a temporary file in the same directory as the destination so the replacement can happen on the same filesystem. Keep backups if overwriting an existing cleaned file would be costly.

Work with Large JSON Files

The examples above load the entire file into memory. This is convenient for small and medium-sized JSON documents, but may not work well for very large files. If your data is stored as one large JSON array, the standard library still needs to parse that document as a whole.

For data you control, consider using JSON Lines, where each line contains one independent JSON value. You can process one record at a time:

import json

with open("records.jsonl", "r", encoding="utf-8") as source, \
     open("records_cleaned.jsonl", "w", encoding="utf-8") as destination:
    for line_number, line in enumerate(source, start=1):
        if not line.strip():
            continue

        record = json.loads(line)
        cleaned_record = clean_strings(record)
        destination.write(json.dumps(cleaned_record, ensure_ascii=False))
        destination.write("\n")

JSON Lines is a different format from a standard JSON array, so use this method only when the file is intended to contain one JSON value per line. For very large standard JSON documents, a streaming parser from a third-party package may be appropriate.

Common Mistakes to Avoid

  • Overwriting the source too early: Write to a separate file until you have checked the output.
  • Assuming every JSON file has the same structure: Check whether the top-level value is a list, object, or another type before filtering it.
  • Changing values without a clear rule: Trimming or lowercasing every string can damage meaningful data.
  • Confusing JSON with Python syntax: JSON uses double quotes and the values true, false, and null, not Python’s True, False, and None.
  • Ignoring encoding: Open text files with an explicit encoding such as utf-8.
  • Skipping validation: Successful parsing confirms JSON syntax, not that the contents match your application’s requirements.

Conclusion

Cleaning a JSON file in Python starts with parsing it using the built-in json module, then applying clear rules to format, normalize, filter, and validate the data. Recursive functions help clean nested values, while list comprehensions make it easy to remove records that do not meet your requirements. Saving to a separate file—and validating the result before using it—helps protect your original data.

Keep cleanup rules specific to your application, handle parsing errors explicitly, and use a streaming approach when your data is too large to load into memory. With these practices, you can build a reliable Python workflow for cleaning JSON files and preparing them for analysis, storage, or use by another system.


Disclaimer: Articles are written by Humans, AI or Both. Verify Important information.

Shrewdnia

Shrewdnia

Shrewdnia is a destination for curious minds seeking clarity, knowledge, and informed perspectives. Through insightful articles and practical guides our passionate team explores a wide range of topics designed to help readers understand the world around them, make smarter decisions, and stay informed in an ever-changing landscape.


💡 Every question sparks discovery, and every perspective enriches the conversation. Share your thoughts and insights in the comments 👇

Back to blog

Leave a comment

JOIN THE SHREWDNIA COMMUNITY FORUM

What do you think?

Have an opinion, experience, or question about this topic? Join the Shrewdnia Forum and share your thoughts with other readers.

Join the Forum →