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
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.

🌐
PYnative
pynative.com › home › python › json › validate json data using python
Validate JSON data using Python
May 14, 2021 - Check if a string is valid JSON in Python. Validate JSON Schema using Python. Validates incoming JSON data by checking if there all necessary fields present in JSON and also verify data types of those fields
Discussions

How do I check if a string is valid JSON in Python? - Stack Overflow
In Python, is there a way to check if a string is valid JSON before trying to parse it? For example working with things like the Facebook Graph API, sometimes it returns JSON, sometimes it could More on stackoverflow.com
🌐 stackoverflow.com
python - Check if file is json loadable - Stack Overflow
I have two types of txt files, one which is saved in some arbitrary format on the form Header key1 value1 key2 value2 and the other file formart is a simple json dump stored as with open(filename... More on stackoverflow.com
🌐 stackoverflow.com
How to check if something is in a JSON object before running if statement
There's no such thing as a "JSON object." There's a JSON string, which represents an object, but once you've deserialized the string you're holding a regular Python dictionary or list. So all of the regular Python membership tests work - you test whether the collection contains a key or a value by using in. The issue that I have run into so that sometimes those attributes (like subtitle) don't exist in the JSON because they do not exist in the file. if "subtitle" not in record or record["subtitle"] != "French": add_french_subtitles(record) # or whatever More on reddit.com
🌐 r/learnpython
11
6
September 15, 2023
python - How to check JSON format validation? - Stack Overflow
My program gets a JSON file that has an information for service. Before run the service program, I want to check if the JSON file is valide(Only check whether all necessary keys exist). Below is the More on stackoverflow.com
🌐 stackoverflow.com
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-check-whether-a-string-is-valid-json-or-not
Python | Check whether a string is valid json or not - GeeksforGeeks
July 11, 2025 - In the below example, the string is an invalid JSON because, the string characters are enclosed in single quotes ('), but as per valid JSON schema, strings must be enclosed in double quotes ("). ... # Python code to demonstrate # checking whether string # is valid json or not import json ini_string = "{'akshat' : 1, 'nikhil' : 2}" # printing initial ini_string print ("initial string", ini_string) # checking for string try: json_object = json.loads(ini_string) print ("Is valid json?
Top answer
1 of 8
344

You can try to do json.loads(), which will throw a ValueError if the string you pass can't be decoded as JSON.

In general, the "Pythonic" philosophy for this kind of situation is called EAFP, for Easier to Ask for Forgiveness than Permission.

2 of 8
238

Example Python script returns a boolean if a string is valid json:

import json

def is_json(myjson):
  try:
    json.loads(myjson)
  except ValueError as e:
    return False
  return True

Which prints:

print is_json("{}")                          #prints True
print is_json("{asdf}")                      #prints False
print is_json('{ "age":100}')                #prints True
print is_json("{'age':100 }")                #prints False
print is_json("{\"age\":100 }")              #prints True
print is_json('{"age":100 }')                #prints True
print is_json('{"foo":[5,6.8],"foo":"bar"}') #prints True

Convert a JSON string to a Python dictionary:

import json
mydict = json.loads('{"foo":"bar"}')
print(mydict['foo'])    #prints bar

mylist = json.loads("[5,6,7]")
print(mylist)
[5, 6, 7]

Convert a python object to JSON string:

foo = {}
foo['gummy'] = 'bear'
print(json.dumps(foo))           #prints {"gummy": "bear"}

If you want access to low-level parsing, don't roll your own, use an existing library: http://www.json.org/

Great tutorial on python JSON module: https://pymotw.com/2/json/

Is String JSON and show syntax errors and error messages:

sudo cpan JSON::XS
echo '{"foo":[5,6.8],"foo":"bar" bar}' > myjson.json
json_xs -t none < myjson.json

Prints:

, or } expected while parsing object/hash, at character offset 28 (before "bar}
at /usr/local/bin/json_xs line 183, <STDIN> line 1.

json_xs is capable of syntax checking, parsing, prittifying, encoding, decoding and more:

https://metacpan.org/pod/json_xs

🌐
Flexiple
flexiple.com › python › python-json-validator
Python JSON Validator - Flexiple
March 28, 2024 - As a result, the JSON validation function detected this discrepancy and reported a "JSON validation error." This example demonstrates how the Python JSON Validator can effectively check the structure and data types of JSON objects against a ...
🌐
PyPI
pypi.org › project › json-checker
json-checker · PyPI
checker_exceptions.CheckerError: Not valid data Or('int', None), current value '666' (str) is not int, current value '666' (str) is not None · If you need validate no required dict key, use OptionalKey · >>> from json_checker import Checker, OptionalKey >>> expected_schema = {'key1': str, OptionalKey('key2'): int} >>> Checker(expected_schema).validate({'key1': 'value'}) {'key1': 'value'} >>> Checker(expected_schema).validate({'key1': 'value', 'key2': 'value2'}) Traceback (most recent call last): ...
      » pip install json-checker
    
Published   Aug 31, 2019
Version   2.0.0
🌐
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.
Find elsewhere
🌐
Real Python
realpython.com › python-json
Working With JSON Data in Python – Real Python
August 20, 2025 - To swiftly check if a JSON file is valid, you can leverage Python’s json.tool. You can run the json.tool module as an executable in the terminal using the -m switch.
🌐
Python Forum
python-forum.io › thread-24649.html
Validate JSON file
February 25, 2020 - 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...
🌐
YouTube
youtube.com › watch
How to validate Json format in python - YouTube
How to validate Json format in pythonPython JSON validatorhttps://www.w3schools.com/python/python_json.asp
Published   July 19, 2022
🌐
TutorialsPoint
tutorialspoint.com › check-whether-a-string-is-valid-json-or-not-in-python
Check whether a string is valid JSON or not in Python
If there is error we consider the JSON string as invalid. ... import json Astring= '{"Mon" : "2pm", "Wed" : "9pm" ,"Fri" : "6pm"}' # Given string print("Given string", Astring) # Validate JSON try: json_obj = json.loads(Astring) print("A valid JSON") except ValueError as e: print("Not a valid JSON") # Checking again Astring= '{"Mon" : 2pm, "Wed" : "9pm" ,"Fri" : "6pm"}' # Given string print("Given string", Astring) # Validate JSON try: json_obj = json.loads(Astring) print("A valid JSON") except ValueError as e: print("Not a valid JSON") # Nested levels Astring = '{ "Timetable": {"Mon" : "2pm", "Wed" : "9pm"}}' # Given string print("Given string", Astring) # Validate JSON try: json_obj = json.loads(Astring) print("A valid JSON") except ValueError as e: print("Not a 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 quotes around lastName data = '{"firstName": "John", lastName: "Doe"}' print validate_json_syntax(data) Run the test to see what output looks like. ... $ python test.py {u'lastName': u'Doe', u'firstName': u'John'} DEBUG: JSON data contains an error False
🌐
Finxter
blog.finxter.com › home › learn python blog › 5 best ways to check whether a string is valid json in python
5 Best Ways to Check Whether a String is Valid JSON in Python - Be on the Right Side of Change
March 11, 2024 - A good quick check to confirm an object’s type after loading but doesn’t provide schema validation. Method 3: JSON Schema Validation. It’s the strongest way to validate both format and schema of JSON data but requires an extra package. Method 4: Python-like JSON validation using ast.literal_eval().
🌐
Reddit
reddit.com › r/learnpython › how to check if something is in a json object before running if statement
r/learnpython on Reddit: How to check if something is in a JSON object before running if statement
September 15, 2023 -

Ok... This is a little complicated... So... Sorry in advance

I have a function that returns attributes of a video file (FFprobe) in a JSON object, and then a little factory that parses the JSON looking for specific attributes, and running if statements on those attributes.

I.E. One of attributes in the JSON is subtitle format. So if the subtitle format != a desired format, then set a variable that is used in another format for encoding the subtitle to the desired format

The issue that I have run into so that sometimes those attributes (like subtitle) don't exist in the JSON because they do not exist in the file.

So I sort of need to check if the attribute in the JSON exists, before I check to see if if that attribute is the desired attribute and start setting variables

How do I do this?

Would it be as simple as:

json_object= json.loads(studentJson)
if "subtitle_format" in json_object: 
    print("Key exist in json_object") 
    print(subtitle_format["ASS"], " is the subtitle format") 
else: 
    print("Key doesn't exist in JSON data")

If yes, would I get yelled at if the if statement had a few layers? Psudo:

if subtitle_format in json_object:
    if subtitle_format == ass
         if subtitle_format == english
             encode 

🌐
Built In
builtin.com › software-engineering-perspectives › python-json-schema
How to Use JSON Schema to Validate JSON Documents in Python | Built In
You can also use Validator.is_valid to check if a JSON is valid or not quietly, with no ValidationError raised if it is invalid.
🌐
Donofden
donofden.com › blog › 2020 › 03 › 15 › How-to-Validate-JSON-Schema-using-Python
How to Validate JSON Schema using Python
We first convert the input JSON in to python object using json.loads then using jsonschema function validate we validate the given input with the JSON Schema provided. If you try to run the above script, the output will be Given JSON data is Valid.
🌐
HitXP
hitxp.com › home › how to check if json string is valid in python?
How to check if JSON string is valid in Python? - HitXP
January 21, 2020 - If you want to check if a given JSON string is in valid JSON format or not, then simply call the function is_valid_json given below. It will return True if the JSON is valid, else will return False. import json #returns True if json_str is a ...
🌐
Towards Data Science
towardsdatascience.com › home › latest › how to use json schema to validate json documents in python
How to Use JSON Schema to Validate JSON Documents in Python | Towards Data Science
March 5, 2025 - You can also use Validator.is_valid to check if a JSON is valid or not quietly, with no ValidationError raised if it is invalid.