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.

Answer from John Flatness on Stack Overflow
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

🌐
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 this example the below code uses a function, `is_valid`, to check JSON string validity with `json.loads()`. It tests the function on three JSON strings containing various data types and prints whether each string is valid or not.
Discussions

Validate JSON data using python - Stack Overflow
I need to create a function that validates incoming json data and returns a python dict. It should check if all necessary fields are present in a json file and also validate the data types of those More on stackoverflow.com
🌐 stackoverflow.com
JSON string validation in Python - Stack Overflow
I need to write a test in Python to validate that the payload I am returning is a valid JSON. import json s = '{"position": NaN, "score": 0.3}' json.loads(s) the code above doesn't throw an exception, while the string is obviously not a valid JSON according to my backend friend and jsonlint.com/. More on stackoverflow.com
🌐 stackoverflow.com
April 20, 2024
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
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
🌐
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
🌐
Flexiple
flexiple.com › python › python-json-validator
Python JSON Validator - Flexiple
March 28, 2024 - The age field was expected to be an integer but contained the string "thirty," which is not a valid integer. 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 ...
🌐
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
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")
Find elsewhere
🌐
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 - This function, is_valid_json_by_schema, verifies whether the JSON string matches a specific schema, providing a way to ensure the data has the correct structure and data types expected. Although not recommended for arbitrary or untrusted input, you can use the ast.literal_eval() to safely evaluate a string containing Python literal structures, which can sometimes resemble JSON objects.
🌐
Testcookbook
testcookbook.com › book › python › json-schema-validation.html
JSON Schema Validation - 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))
🌐
W3Resource
w3resource.com › JSON › snippets › json-validator-explained-with-python-code-and-examples.php
JSON Validator with Examples
November 7, 2025 - Validation ensures the data is properly formatted, which is crucial for seamless communication between systems or APIs. ... 3. Interoperability: Ensures JSON data is compatible with systems or APIs expecting correctly formatted data. ... # 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)
🌐
Soumendrak
blog.soumendrak.com › how-to-validate-a-json-in-python
Soumendra Kumar Sahoo • How to validate a JSON in Python
November 22, 2019 - Here is an example of how to use JSONSchema validation in Python: First, we need to install the jsonschema Library. You can do this using pip: ... Next, we’ll create a JSON schema that defines the structure of our expected data. Here’s an example schema: schema = { "type": "object", "properties": { "name": {"type": "string"}, "age": {"type": "integer"}, "email": {"type": "string", "format": "email"}, "address": {"type": "string"} }, "required": ["name", "age"] }
🌐
Couchbase
couchbase.com › home › validate json documents in python using pydantic
Validate JSON Documents in Python using Pydantic
June 14, 2025 - The syntax for specifying the schema ... in Python. Developers can specify the schema by defining a model. Pydantic has a rich set of features to do a variety of JSON validations. We will walk through the representation for some user profile document specifications. One thing to note about pydantic is that, by default, it tries to coerce the data types by doing type conversions when possible—for example, converting string ‘1’ into ...
🌐
GitHub
github.com › donofden › python-validate-json-schema
GitHub - donofden/python-validate-json-schema: Validate JSON Schema using Python
This is a helper project for JSON Schema validation in Python, which uses Jsonschema the most complete and compliant JSON Schema validator. Validate the necessary fields present in JSON file · 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.
Starred by 6 users
Forked by 2 users
Languages   Python 100.0% | Python 100.0%
🌐
Donofden
donofden.com › blog › 2020 › 03 › 15 › How-to-Validate-JSON-Schema-using-Python
How to Validate JSON Schema using Python
Lets test with alternative json input, If you check th python script above The validate() method will raise an exception if given JSON is not what is described in the schema. {"id" : "10","name": "DonOfDen","contact_number":1234567890} In the ...
🌐
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
July 23, 2025 - In Python, we can use the jsonschema library to validate a JSON instance (can also be referred to as JSON document as long as it’s unambiguous) against a schema. It can be installed with pip: Let’s validate some JSON instances against the ...
🌐
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 

🌐
CodeRivers
coderivers.org › blog › python-validate-json
Python Validate JSON: A Comprehensive Guide - CodeRivers
April 18, 2025 - Python has a built - in json module that can be used to work with JSON data. To validate a JSON string, you can use the json.loads() function. This function attempts to parse the JSON string.
🌐
Pydantic
docs.pydantic.dev › latest › concepts › json
JSON - Pydantic Validation
""" try: return handler(v) except ValidationError as exc: # there might be other types of errors resulting from partial JSON parsing # that you allow here, feel free to customize as needed if all(e['type'] == 'missing' for e in exc.errors()): raise pydantic_core.PydanticUseDefault() else: raise class NestedModel(BaseModel): x: int y: str class MyModel(BaseModel): foo: Optional[str] = None bar: Annotated[ Optional[tuple[str, int]], WrapValidator(default_on_error) ] = None nested: Annotated[ Optional[NestedModel], WrapValidator(default_on_error) ] = None m = MyModel.model_validate( pydantic_core