The built-in JSON module can be used as a validator:

import json

def parse(text):
    try:
        return json.loads(text)
    except ValueError as e:
        print('invalid json: %s' % e)
        return None # or: raise

You can make it work with files by using:

with open(filename) as f:
    return json.load(f)

instead of json.loads and you can include the filename as well in the error message.

On Python 3.3.5, for {test: "foo"}, I get:

invalid json: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)

and on 2.7.6:

invalid json: Expecting property name: line 1 column 2 (char 1)

This is because the correct json is {"test": "foo"}.

When handling the invalid files, it is best to not process them any further. You can build a skipped.txt file listing the files with the error, so they can be checked and fixed by hand.

If possible, you should check the site/program that generated the invalid json files, fix that and then re-generate the json file. Otherwise, you are going to keep having new files that are invalid JSON.

Failing that, you will need to write a custom json parser that fixes common errors. With that, you should be putting the original under source control (or archived), so you can see and check the differences that the automated tool fixes (as a sanity check). Ambiguous cases should be fixed by hand.

Answer from reece on Stack Overflow
🌐
PYnative
pynative.com › home › python › json › validate json data using python
Validate JSON data using Python
May 14, 2021 - Note: Use json.load() method instead of json.loads() to parse and validate JSON from a file. Python provides The json.tool module to validate JSON objects from the command line.
Top answer
1 of 4
54

The built-in JSON module can be used as a validator:

import json

def parse(text):
    try:
        return json.loads(text)
    except ValueError as e:
        print('invalid json: %s' % e)
        return None # or: raise

You can make it work with files by using:

with open(filename) as f:
    return json.load(f)

instead of json.loads and you can include the filename as well in the error message.

On Python 3.3.5, for {test: "foo"}, I get:

invalid json: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)

and on 2.7.6:

invalid json: Expecting property name: line 1 column 2 (char 1)

This is because the correct json is {"test": "foo"}.

When handling the invalid files, it is best to not process them any further. You can build a skipped.txt file listing the files with the error, so they can be checked and fixed by hand.

If possible, you should check the site/program that generated the invalid json files, fix that and then re-generate the json file. Otherwise, you are going to keep having new files that are invalid JSON.

Failing that, you will need to write a custom json parser that fixes common errors. With that, you should be putting the original under source control (or archived), so you can see and check the differences that the automated tool fixes (as a sanity check). Ambiguous cases should be fixed by hand.

2 of 4
3

Yes, there are ways to validate that a JSON file is valid. One way is to use a JSON parsing library that will throw exceptions if the input you provide is not well-formatted.

try:
   load_json_file(filename)
except InvalidDataException: # or something
   # oops guess it's not valid

Of course, if you want to fix it, you naturally cannot use a JSON loader since, well, it's not valid JSON in the first place. Unless the library you're using will automatically fix things for you, in which case you probably wouldn't even have this question.

One way is to load the file manually and tokenize it and attempt to detect errors and try to fix them as you go, but I'm sure there are cases where the error is just not possible to fix automatically and would be better off throwing an error and asking the user to fix their files.

I have not written a JSON fixer myself so I can't provide any details on how you might go about actually fixing errors.

However I am not sure whether it would be a good idea to fix all errors, since then you'd have assume your fixes are what the user actually wants. If it's a missing comma or they have an extra trailing comma, then that might be OK, but there may be cases where it is ambiguous what the user wants.

🌐
Real Python
realpython.com › python-json
Working With JSON Data in Python – Real Python
August 20, 2025 - You can use Python’s json.tool module in the command line to validate JSON syntax by running python -m json.tool <filename>.
🌐
GitHub
gist.github.com › kamiller › 3177943
validate json with python via bash script · GitHub
validate json with python via bash script · Raw · validate_json.sh · This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
🌐
Juha-Matti Santala
hamatti.org › posts › pretty-print-and-validate-json-on-command-line-with-json-tool
Pretty print and validate JSON on command line with json.tool : Juha-Matti Santala
August 25, 2024 - Python is not only a great programming language but its built-in command line tools make it a nice companion on terminal as well. Today’s small but powerful example is using json.tool from json module as a command line tool to pretty print and validate JSON. Let’s say we have a JSON file ...
🌐
Linux Hint
linuxhint.com › validate-json-files-from-command-line-linux
How to Validate JSON from the Command Line on Linux – Linux Hint
Validating JSON from the command line can be done using JSON Spec, jq and jsonlint. These tools can validate the JSON data, providing feedback on any errors.
Find elsewhere
🌐
Python Forum
python-forum.io › thread-24649.html
Validate JSON file
Hi, I am new to the python language (well new to any programming language). From what I have been reding on-line, python has components to validate JSON files, which is what I need to do. In stalled Python 3.81 and found a script on-line that says i...
🌐
JSONLint
jsonlint.com
JSONLint - The JSON Validator
The best way to find and correct errors while simultaneously saving time is to use an online tool such as JSONLint. JSONLint will check the validity of your JSON code, detect and point out line numbers of the code containing errors.
🌐
Commandlinefu
commandlinefu.com › commands › view › 5074 › validate-json
validate json
curl -s -X POST http://www.jsonlint.com/ajax/validate -d json="`cat file.js`" -d reformat=no · I have this saved as jsonlint chmodded +x and file.js is instead $1, but YMMV ... Can also be done using python http://www.commandlinefu.com/commands/view/2144/validate-and-pretty-print-json-expressions.
🌐
Built In
builtin.com › software-engineering-perspectives › python-json-schema
How to Use JSON Schema to Validate JSON Documents in Python | Built In
We now know how to define the schema ... a JSON document against a schema is jsonschema, which can be installed using pip install jsonschema....
🌐
Xmodulo
xmodulo.com › validate-json-command-line-linux.html
How to validate JSON from the command line on Linux
This tutorial describes how to validate JSON data and JSON schema from the command line on Linux.
🌐
GitHub
github.com › zaach › jsonlint
GitHub - zaach/jsonlint: A JSON parser and validator with a CLI. · GitHub
Install jsonlint with npm to use the command line interface: ... $ jsonlint -h Usage: jsonlint [file] [options] file file to parse; otherwise uses stdin Options: -v, --version print version and exit -s, --sort-keys sort object keys -i, --in-place overwrite the file -t CHAR, --indent CHAR character(s) to use for indentation [ ] -c, --compact compact error display -V, --validate a JSON schema to use for validation -e, --environment which specification of JSON Schema the validation file uses [json-schema-draft-03] -q, --quiet do not print the parsed json to STDOUT [false] -p, --pretty-print force pretty printing even if invalid
Starred by 2K users
Forked by 415 users
Languages   JavaScript 91.2% | HTML 3.8% | Yacc 3.0% | Lex 1.1% | Makefile 0.9%
🌐
Lindevs
lindevs.com › format-and-validate-json-with-cli-tool-in-python-3-14
Format and Validate JSON with CLI Tool in Python 3.14 | Lindevs
January 9, 2026 - For existing scripts, the previous command still works: ... However, for new workflows, python -m json is the recommended approach. ... When working with ONNX models, it's important to ensure their validity before deployment to avoid...
🌐
CodeSpeedy
codespeedy.com › home › validate json data using python
Validate JSON data using Python - CodeSpeedy
January 8, 2022 - MySchema = { "type": "object", "properties": { "name": {"type": "string"}, "roll": {"type": "number"}, "marks": {"type": "number"}, }, } #function for cheking validation of JSOn data def validateJson(jsonData): #we define try except for handling ...
🌐
GeeksforGeeks
geeksforgeeks.org › python-check-whether-a-string-is-valid-json-or-not
Python | Check whether a string is valid json or not - GeeksforGeeks
December 14, 2023 - In the below example, the string ... print ("initial string", ini_string) # checking for string try: json_object = json.loads(ini_string) print ("Is valid json?...
🌐
Testcookbook
testcookbook.com › book › python › json-schema-validation.html
JSON Schema Validation - Test Cookbook
import json def validate_json_syntax(d): try: return json.loads(d) except ValueError: print('DEBUG: JSON data contains an error') return False #will return the data data = '{"firstName": "John", "lastName": "Doe"}' print validate_json_syntax(data) #will return false because JSON not valid #missing ...