How to Check if key Error key exist in a JSON String Python

If i want to check if my JSON String contain Error from API request, i have a string that saved the respond, Example

final = response.json()

And i want to check if the API response error

By Damola Ajibade via Discussions on Python.org at 24Sep2022 16:09:

If i want to check if my JSON String contain Error from API request, i
have a string that saved the respond, Example

final = response.json()

And i want to check if the API response error

It depends on the API - note that the response HTTP code can also
indicate an error. But assuming that’s good, you want to decode the JSON
into a Python object (typically a dict) and inspect the dict. I tend
to use a suffix on the variable names to keep track of what’s what.
Example:

 import json
 ........
 final_js = response.json()
 final = json.loads(final_js)
 ... look a what's in `final` now ...

But I thoughout that in the requests package, response.json()
actually decoded the JSON response for you, and so your final above
is already a dict and not a JSON string. So you should not need to
use json.loads() to turn it into something.

What does:

 print(type(final))

tell you about the type of final? Is it a str (i.e. not yet decoded
JSON) or something else, probably a dict, indicating that the JSON has
already been decoded for you? If the latter, what does:

 print(repr(final))

do for you? For biggish structures:

 from pprint import pprint
 .............
 pprint(final)

will produce an easier to understand printout.

Cheers,
Cameron Simpson cs@cskk.id.au