If you haven't check jsonschema library, it can be useful to validate data. JSON Schema is a way to describe the content of JSON. The library just uses the format to make validations based on the given schema.

I made a simple example from basic usage.

import json
from jsonschema import validate

# Describe what kind of json you expect.
schema = {
    "type" : "object",
    "properties" : {
        "description" : {"type" : "string"},
        "status" : {"type" : "boolean"},
        "value_a" : {"type" : "number"},
        "value_b" : {"type" : "number"},
    },
}

# Convert json to python object.
my_json = json.loads('{"description": "Hello world!", "status": true, "value_a": 1, "value_b": 3.14}')

# Validate will raise exception if given json is not
# what is described in schema.
validate(instance=my_json, schema=schema)

# print for debug
print(my_json)
Answer from T.Nylund on Stack Overflow
🌐
Built In
builtin.com › software-engineering-perspectives › python-json-schema
How to Use JSON Schema to Validate JSON Documents in Python | Built In
In Python, we can use the JSON Schema library to validate a JSON document against a schema. ... Summary: The jsonschema library validates JSON data against schemas, utilizing keywords like type, properties, and required.
Discussions

How do I check if a string is valid JSON in Python? - Stack Overflow
just a note... json.loads('10') doesn't throw the ValueError and I'm sure '10' is not a valid json ... 2014-04-16T13:23:01.363Z+00:00 ... Despite the fact that the spec says that a JSON text must be an array or object, most encoders and decoders (including Python's) will work with any JSON ... More on stackoverflow.com
🌐 stackoverflow.com
I wrote okjson - A fast, simple, and pythonic JSON Schema Validator
https://github.com/mufeedvh/okjson/blob/main/okjson/validator.py It's useful to use a formatter/linter and configure your text editor to be aligned with the linter. $> pylint okjson | grep 'Bad indentation' | wc -l 100 black is a popular formatter used by the community. https://github.com/psf/black pylint is a useful listing tool. https://pylint.pycqa.org/en/latest/ Best of luck to you on your project. More on reddit.com
🌐 r/Python
4
14
March 31, 2022
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
How to validate a json file
I wonder if you're getting a chunked response and only seeing the first chunk? If it were me, I'd put a breakpoint in and check what response.content was. Somewhere in your process you're losing data, or never receiving it to begin with - although, if the .json() method is not throwing an error, then the response should be complete json content I would have thought... You could also try just writing the response.content to file as is, and bypass the json() and dump() methods? More on reddit.com
🌐 r/learnpython
4
2
August 31, 2022
🌐
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
🌐
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 - # 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?
🌐
Flexiple
flexiple.com › python › python-json-validator
Python JSON Validator - Flexiple
March 28, 2024 - In this blog, we explored the Python JSON Validator, a powerful tool for ensuring the validity of JSON data. By defining a JSON schema and using the json.JSONValidator class, we can easily validate JSON objects against the specified structure.
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

🌐
GitHub
github.com › donofden › python-validate-json-schema
GitHub - donofden/python-validate-json-schema: Validate JSON Schema using Python
Validate JSON Field type. We need data of a JSON filed in a type that we want. For example, we want all numeric fields in the number format instead of number encoded in a string format like this Marks: "75" so we can use it directly instead of checking and converting it every time. To learn the implementation of Jsonschema in python. To implement,JSON Conversion to Python Object using json.load or json.loads methods.
Starred by 6 users
Forked by 2 users
Languages   Python 100.0% | Python 100.0%
Find elsewhere
🌐
Couchbase
couchbase.com › home › validate json documents in python using pydantic
Validate JSON Documents in Python using Pydantic
June 14, 2025 - This user profile example shows how we can easily create custom schemas for our JSON documents. This post also shows how to use the test and validate capabilities of Python and the pydantic module.
🌐
jsonschema
python-jsonschema.readthedocs.io › en › stable › validate
Schema Validation - jsonschema 4.26.0 documentation
conforms(instance: object, format: str) → bool[source] Check whether the instance conforms to the given format. ... Validating a format failed. The JSON Schema specification recommends (but does not require) that implementations use ECMA 262 regular expressions. Given that there is no current library in Python capable of supporting the ECMA 262 dialect, the regex format will instead validate Python regular expressions, which are the ones used by this implementation for other keywords like pattern or patternProperties.
🌐
Testcookbook
testcookbook.com › book › python › json-schema-validation.html
Validating JSON with Python - Test Cookbook
import json from jsonschema import validate def validate_json_syntax(d): try: return json.loads(d) except ValueError: print('DEBUG: JSON data contains an error') return False data = '{"firstName": "John", "lastName": "Doe"}' jsd = validate_json_syntax(data) schema = { "type": "object", "properties": { "firstName": { "type": "string"}, "lastName": { "type": "string"} } } #output will be None print(validate(jsd, schema))
🌐
PyPI
pypi.org › project › json-checker
json-checker · PyPI
Here is a quick example to get a feeling of json_checker, validating a list of entries with personal information: >>> from json_checker import Checker >>> current_data = {'first_key': 1, 'second_key': '2'} >>> expected_schema = {'first_key': int, 'second_key': str} >>> checker = Checker(expected_schema) >>> result = checker.validate(current_data) >>> assert result == current_data
      » pip install json-checker
    
Published   Aug 31, 2019
Version   2.0.0
🌐
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 - Each field of the target JSON is specified as a key/value pair, with the key being the actual field name and the value being the type of the field in the target JSON. The type keyword for each field has the same meaning as the top-level one. As you may imagine, the type here can also be object. In this case, the corresponding field would be a nested object, as will be demonstrated later. The required keyword is an array containing the properties that are required to be present. If any property specified here is missing, a ValidationError will be raised.
🌐
jsonschema
python-jsonschema.readthedocs.io › en › latest › validate
Schema Validation - jsonschema 4.26.1.dev25+gad0a1b301 documentation
conforms(instance: object, format: str) → bool[source] Check whether the instance conforms to the given format. ... Validating a format failed. The JSON Schema specification recommends (but does not require) that implementations use ECMA 262 regular expressions. Given that there is no current library in Python capable of supporting the ECMA 262 dialect, the regex format will instead validate Python regular expressions, which are the ones used by this implementation for other keywords like pattern or patternProperties.
🌐
Donofden
donofden.com › blog › 2020 › 03 › 15 › How-to-Validate-JSON-Schema-using-Python
How to Validate JSON Schema using Python
March 15, 2020 - execute_api_schema = get_schema() try: validate(instance=json_data, schema=execute_api_schema) except jsonschema.exceptions.ValidationError as err: print(err) err = "Given JSON data is InValid" return False, err message = "Given JSON data is Valid" return True, message # Convert json to python object.
🌐
jsonschema
python-jsonschema.readthedocs.io
jsonschema 4.26.0 documentation
>>> validate(instance={"name" : ... ... ValidationError: 'Invalid' is not of type 'number' It can also be used from the command line by installing check-jsonschema....
🌐
Python
docs.python.org › 3 › library › json.html
JSON encoder and decoder — Python 3.14.3 documentation
February 23, 2026 - The json module can be invoked as a script via python -m json to validate and pretty-print JSON objects.
🌐
W3Resource
w3resource.com › JSON › snippets › json-validator-explained-with-python-code-and-examples.php
JSON Validator with Examples
November 7, 2025 - # Import the json module import json # Define a JSON string json_data = ''' { "name": "Zara Sara", "age": 30, "skills": ["Python", "JavaScript", "SQL"], "isEmployed": true } ''' # Function to validate JSON def validate_json(data): try: # Attempt to parse the JSON string json.loads(data) # Convert JSON string to Python object print("The JSON is valid.") except json.JSONDecodeError as e: # Handle JSON syntax errors print("Invalid JSON:", e) # Validate the JSON string validate_json(json_data)
🌐
LinkedIn
linkedin.com › pulse › mastering-json-schema-validation-python-developers-guide-singh-ebffc
Mastering JSON Schema Validation with Python: A Developer’s Guide
February 16, 2024 - From basic type checks to intricate conditional validations, JSON Schema is a boon for developers. JSON Schema sets the stage by defining the acceptable data types (like strings, integers, arrays) and structures (such as specific properties within objects). It provides a comprehensive guide for shaping your JSON data. To kick off, ensure your Python ...
🌐
Soumendrak
soumendrak.com › blog › how-to-validate-a-json-in-python
Soumendra Kumar Sahoo • How to validate a JSON in Python
January 13, 2024 - Use the jsonschema library for ... schema). For object-oriented validation, use Pydantic models which parse and validate JSON into typed Python objects automatically....
🌐
GitHub
github.com › python-jsonschema › jsonschema
GitHub - python-jsonschema/jsonschema: An implementation of the JSON Schema specification for Python · GitHub
>>> validate(instance={"name" : "Eggs", "price" : 34.99}, schema=schema) >>> validate( ... instance={"name" : "Eggs", "price" : "Invalid"}, schema=schema, ... ) # doctest: +IGNORE_EXCEPTION_DETAIL Traceback (most recent call last): ... ValidationError: 'Invalid' is not of type 'number' It can also be used from the command line by installing check-jsonschema.
Starred by 4.9K users
Forked by 611 users
Languages   Python 99.8% | TypeScript 0.2%