Your Search Bar For Shrewd Tips

How To Clean Json File


JSON files are used to store settings, web data, API responses, and application records. When a JSON file contains inconsistent formatting, unwanted values, duplicate fields, or invalid syntax, it can be difficult to read and may fail to load. Learning how to clean a JSON file helps you make the data easier to inspect, share, and process—without accidentally changing what it means.

The safest approach is to keep an original copy, check that the file is valid JSON, and make only intentional changes. You can clean JSON with a code editor, a command-line tool such as jq, or a short script in Python. This guide explains each step and shows how to format, validate, and remove unwanted data safely.

What Does It Mean to Clean a JSON File?

Cleaning a JSON file means improving its structure, consistency, or contents while keeping the data valid and preserving the information you need. The right cleanup depends on the problem. A file that is hard to read may only need indentation, while a file containing test records may need specific entries removed.

Common JSON cleanup tasks include:

  • Formatting compact JSON so it is easier to read.
  • Fixing syntax errors such as missing commas or quotation marks.
  • Removing unwanted records, fields, or values.
  • Standardizing inconsistent field names or data formats.
  • Checking that the cleaned file can be parsed by the application that uses it.

Cleaning does not always mean deleting data. For example, a value of false, a number such as 0, or an empty array may be meaningful. Decide what should change before you remove or replace anything.

1. Make a Backup Before Editing

Start by creating a copy of the original file. Save the copy with a clear name, such as data-original.json, and do your work on a separate file. This gives you a way to restore the source if a cleanup rule removes important information or introduces an error.

For important data, keep the original in a secure location and record what you changed. If the JSON file is part of a project managed with version control, review the changes before saving them. A backup is especially useful when cleaning files from a production system, a customer export, or an API integration.

2. Check Whether the File Is Valid JSON

Before changing the contents, determine whether the file is valid JSON. JSON has strict syntax rules: strings and object keys must use double quotation marks, commas separate items, and trailing commas are not allowed. The file must also contain a valid JSON value, such as an object, array, string, number, Boolean, or null.

For example, this is valid JSON:

{
  "name": "Sam",
  "active": true,
  "items": ["book", "lamp"]
}

This similar example is invalid because it uses single quotes and includes a trailing comma:

{
  'name': 'Sam',
  "active": true,
}

A JSON validator or parser can identify where a syntax error occurs. Be careful when fixing the reported location: a missing comma or quotation mark can sometimes cause the parser to flag a later line instead of the actual source of the problem.

3. Format and Beautify the JSON

If the JSON is valid but difficult to read, format it with consistent indentation. This process is often called pretty-printing or beautifying. Formatting changes whitespace and line breaks, not the underlying data.

Many code editors can format JSON automatically. Open the file, choose the editor’s format or pretty-print command, and save a new copy. You can also use Python’s built-in JSON tool from a terminal:

python -m json.tool input.json output.json

This reads input.json, validates it, and writes an indented version to output.json. If the file is invalid, Python displays an error instead of producing a correctly formatted result. Keep the source file until you have checked the output.

Another option is jq, a command-line JSON processor. To format a file, run:

jq . input.json > output.json

Both tools are useful for large files because they can format data without requiring you to make manual changes throughout the document.

4. Remove Unwanted Data Carefully

Once the file is valid and readable, identify exactly what you want to remove. You might need to delete a test record, remove a field that is no longer used, or exclude entries that meet a particular condition. Make cleanup rules specific, and check how they affect nested objects and arrays.

For instance, if an array contains user records and you want to remove records marked as inactive, filter on that field rather than deleting every record with a missing value. A clear rule is easier to review and less likely to remove useful data.

A common mistake is deleting all “empty” values with a broad rule. These values are not interchangeable:

  • null may indicate that a value is unknown or intentionally absent.
  • "" is an empty string and may be a valid user response.
  • 0 is a number and can be a meaningful quantity or identifier.
  • false is a Boolean value that may represent a real setting.
  • [] and {} are valid empty arrays and objects.

Remove a value only when you know it is unwanted for the file’s intended use. If another system expects a particular field, deleting it could cause a validation error or change the behavior of an application.

5. Clean a JSON File with Python

Python is a practical choice when you need repeatable cleanup rules. Its built-in json module can load, edit, and write JSON without installing an additional package. The following example removes dictionary entries whose value is null, while keeping empty strings, zero, and false.

import json

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

def remove_null_values(value):
    if isinstance(value, dict):
        return {
            key: remove_null_values(item)
            for key, item in value.items()
            if item is not None
        }
    if isinstance(value, list):
        return [remove_null_values(item) for item in value]
    return value

cleaned_data = remove_null_values(data)

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

This script works recursively, so it checks objects nested inside other objects and arrays. Use it only if removing every null value is appropriate for your data. To remove empty strings instead, change the condition deliberately; do not use a general “falsey” check, because that can also match 0, false, and empty containers.

For example, a rule such as if item treats several different values as false. That may silently remove valid information. Explicit checks make your cleanup script easier to understand and safer to maintain.

6. Clean JSON from the Command Line with jq

jq can format, filter, and transform JSON directly from a terminal. It is especially helpful when working with large files or when you need to apply the same cleanup to multiple files. The exact filter depends on the shape of your data.

For example, if the top-level JSON value is an array of records and each record has an active field, this command keeps only active records:

jq '[.[] | select(.active == true)]' input.json > cleaned.json

If the top-level value is an object containing a users array, the filter must refer to that path instead. Preview the output in the terminal before writing over any file. jq filters are powerful, but a filter designed for an array will not work as intended on an object or a different data structure.

7. Watch for Duplicate Keys and Non-JSON Syntax

Some files look like JSON but are actually JSON-like formats, such as JSONC, which allows comments. Standard JSON does not allow comments, so a strict parser may reject lines containing // or comment blocks. If the file belongs to an application that supports JSONC, use a compatible tool rather than removing comments blindly.

Duplicate keys are another issue to check. An object like {"color":"blue","color":"green"} contains the same key twice. Some parsers accept it and keep only one value, while others may handle it differently. Because the result can vary between tools, remove duplicates intentionally and confirm which value should remain.

Do not try to fix a JSON file with broad search-and-replace operations unless you understand the structure. Replacing every single quote, deleting every comment marker, or removing every comma can damage text values or create new syntax errors.

8. Validate the Cleaned File

After editing, validate the cleaned file again. Open it with the same parser or tool that will be used by the target application. Then compare the output with the original to confirm that only intended changes were made.

Before considering the file finished, check that:

  • The file parses successfully as the expected JSON format.
  • Required keys and records are still present.
  • Values such as zero, false, and empty arrays were not removed by mistake.
  • The file uses the expected encoding, usually UTF-8.
  • The application or workflow that reads the file accepts the cleaned version.

If the file contains personal, financial, or confidential information, avoid pasting it into a public online JSON formatter. Use a trusted local editor or command-line tool instead, and follow your organization’s data-handling policies.

Common Mistakes When Cleaning JSON

Most JSON cleanup problems happen when someone changes data without understanding how it is used. Formatting alone is generally low risk, but removing fields or transforming values can affect software, reports, and downstream processes.

  • Overwriting the original file before confirming the cleaned output.
  • Removing all empty-looking values, including meaningful zeros or Boolean values.
  • Assuming a file with comments is standard JSON.
  • Using a cleanup script that handles only the top level and ignores nested data.
  • Changing field names without checking which applications depend on them.
  • Skipping validation after the cleanup is complete.

Conclusion

To clean a JSON file safely, make a backup, validate the source, and choose a cleanup method that matches the problem. Use a formatter to improve readability, a parser to catch syntax errors, or Python and jq to apply precise rules to records and fields. Treat values such as null, empty strings, zero, and false according to their meaning—not as interchangeable clutter.

Finally, validate the cleaned JSON and test it in the system that will use it. A careful, repeatable process keeps the file readable and reliable while protecting the data your application needs.


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 →