If you simply need to check that the request was successful, using request.status_code will do the trick:

def test_case_connection():
    req = requests.get_simple(url=Server.MY_SERVER, params=my_vars)
    assert req.status_code == 200

If you want instead to check for the presence of a specific key-value pair in the response, you need to convert your response payload from json to a dict:

import json

def test_case_connection():
    req = requests.get_simple(url=Server.MY_SERVER, params=my_vars)
    data = json.loads(req.content)
    assert data["status"] == "0"

If you are using the Requests library you can avoid converting json manually by using its builtin json decoder.

Answer from Railslide on Stack Overflow
🌐
Medium
medium.com › grammofy › testing-your-python-api-app-with-json-schema-52677fe73351
Testing Your Python API App with JSON Schema | by Paul Götze | Grammofy | Medium
August 21, 2020 - Let’s suppose we have a simple JSON response for a user endpoint GET /users/:id: Here is an example how you would naively test this response by checking the presence of the properties (client would be a pytest fixture, e.g. a test_client of your Flask app): ... Grammofy is a streaming service for classical music.
🌐
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
🌐
Skyscreamer
jsonassert.skyscreamer.org
JSONAssert - Write JSON Unit Tests with Less Code - Introduction
JSONObject data = getRESTData("/friends/367.json"); Assert.assertTrue(data.has("friends")); Object friendsObject = data.get("friends"); Assert.assertTrue(friendsObject instanceof JSONArray); JSONArray friends = (JSONArray) friendsObject; Assert.assertEquals(2, data.length()); JSONObject friend1Obj = friends.getJSONObject(data.get(0)); Assert.true(friend1Obj.has("id")); Assert.true(friend1Obj.has("name")); JSONObject friend2Obj = friends.getJSONObject(data.get(1)); Assert.true(friend2Obj.has("id")); Assert.true(friend2Obj.has("name")); if ("Carter Page".equals(friend1Obj.getString("name"))) { A
🌐
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.
🌐
automation hacks
automationhacks.io › home › 2020 › 12 › 25
Python API test automation framework (Part 5) Working with JSON and JsonPath - automation hacks
December 25, 2020 - For our case, let’s say we want to perform the same action that we did earlier. i.e. get all the persons name and then check if the one that we expect is present inside the list. We can specify the JSON path expression using the parse("$.[*].lname") method ... To get this JSON path to execute we call the find() method and give it the response JSON from the GET API response. Finally, we assert that our expected last name is indeed present inside this list of users and fail if not found.
🌐
GitHub
gist.github.com › NelsonMinar › 28c5928adbe1f4502af8
Testing various dict wrappers for Python JSON · GitHub
Testing various dict wrappers for Python JSON · Raw · python-json-types.py · 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.
🌐
Testcookbook
testcookbook.com › book › python › json-schema-validation.html
JSON Schema Validation - Test Cookbook
$ python test.py {u'lastName': u'Doe', u'firstName': u'John'} DEBUG: JSON data contains an error False · Once we have loaded the JSON and we know that it is syntactically correct. We can now start testing the JSON schema.
🌐
PyPI
pypi.org › project › json-checker
json-checker · PyPI
json_checker is a library for validating Python data structures, such as those obtained from JSON (or something else) to Python data-types. json_checker has a parameter (soft=True) that allows you validate all json and raise all errors after validation done, it`s very profitable from API testing: >>> import requests >>> >>> from json_checker import Checker >>> >>> >>> def test_api(): >>> res = requests.get(API_URL).json() >>> assert Checker(EXPECTED_RESPONSE, soft=True).validate(res) == res ·
      » pip install json-checker
    
Published   Aug 31, 2019
Version   2.0.0
Find elsewhere
🌐
Stack Overflow
stackoverflow.com › questions › 29637076 › python-unittest-for-method-returning-json-string
Python Unittest for method returning json string - Stack Overflow
You might find this easier if you split it into more separate parts - testing whether a method can correctly parse a JSON string should be trivial. Could you post the method, with a minimal class skeleton around it? ... If your method under test is supposed to "read the status correctly", then you might want to specifically test that. ... def test_read_status(self): mock_input_val = {'something': 'good val'} expected_positive_return_val = something self.assertEqual(read_status(json.dumps(mock_input_val)), expected_positive_return_val)
🌐
Blogger
hanxue-it.blogspot.com › 2017 › 10 › pytest-testing-and-comparing-json-response-using-pytest-flask.html
Hanxue and IT: Pytest: Testing and Comparing JSON Response Using Pytest-Flask
October 18, 2017 - Let's say we have a Flask API endpoint that returns this JSON { "message": "Staff name and password pair not match", "errors": { ...
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

🌐
Stack Overflow
stackoverflow.com › questions › 74570926 › how-to-assert-data-in-a-json-array-with-python
How to assert data in a JSON array with Python - Stack Overflow
# response = json.loads(api_response_data) response = { "data": [ { "user": "test1", "userName": "John Berner", "userid": "1" }, { "user": "test2", "userName": "Nick Morris", "userid": "2" } ], "metadata": { "current_page": 1, "pages": 1, "per_page": 100, "total": 2 } } user_info = { "user": "test1", "userName": "John Berner", "userid": "1" } assert user_info in response['data'] Above doesn't raise AssertionError because the user_info is there in the response['data']
🌐
FastAPI
fastapi.tiangolo.com › tutorial › testing
Testing - FastAPI
Because this file is in the same package, you can use relative imports to import the object app from the main module (main.py): Python 3.10+ from fastapi.testclient import TestClient from .main import app client = TestClient(app) def test_read_main(): response = client.get("/") assert response.status_code == 200 assert response.json() == {"msg": "Hello World"} ...and have the code for the tests just like before.
🌐
GitHub
github.com › davidpdrsn › assert-json-diff
GitHub - davidpdrsn/assert-json-diff: Easily compare two JSON values and get great output
This crate includes macros for comparing two serializable values by diffing their JSON representations. It is designed to give much more helpful error messages than the standard assert_eq!. It basically does a diff of the two objects and tells you the exact differences.
Starred by 90 users
Forked by 18 users
Languages   Rust 97.4% | Shell 2.6% | Rust 97.4% | Shell 2.6%
🌐
Qabash
qabash.com › practical-json-patterns-api-to-assertions-in-pytest
Practical JSON Patterns: API to Assertions in PyTest - QAbash.com
August 13, 2025 - Helpful tools include: json, jmespath, DeepDiff, jsonschema, Pydantic, and even PyHamcrest for expressive assertions. ... Use retry mechanisms, log actual JSON responses on failure, and keep tests focused on stable fields only. If you’re working with APIs in Python, mastering JSON is no longer a nice-to-have — it’s a superpower.
🌐
jsonschema
python-jsonschema.readthedocs.io › en › stable › validate
Schema Validation - jsonschema 4.26.0 documentation
Most of the documentation for this package assumes you’re familiar with the fundamentals of writing JSON schemas themselves, and focuses on how this library helps you validate with them in Python. If you aren’t already comfortable with writing schemas and need an introduction which teaches about JSON Schema the specification, you may find Understanding JSON Schema to be a good read! The simplest way to validate an instance under a given schema is to use the validate function.
🌐
Medium
medium.com › @qebuzzz › validating-and-asserting-responses-in-python-requests-14b40908327a
Validating and Asserting Responses in Python Requests | by Qebuzzz | Medium
August 8, 2023 - If the header is not present in the response, content_type will be set to None. assert content_type == “application/json; charset=utf-8”, “Unexpected Content-Type: “ + content_type: This line is the test assertion.