While parsing a large JSON, it’s possible that some keys may only exist in certain circumstances, such as when an error is present. It’s not uncommon to get a 200 OK
from the server’s API, but then the response you got contains errors that should be checked for.
What’s the best way to handle this?
I know that using things like get()
are one way to handle KeyErrors.
if json.get('errors') is not None:
do_something
But what if we need to keep going? This feels horrible:
if json.get('errors') is not None:
if json.get('errors').get('code') is not None:
if json.get('errors').get('code') != 0:
this_is_bad_throw_error
Is there a better way? For example, ruby
has a dig()
method that basically condenses that whole line into x = dig(:errors, :code)
and then you just check on x
if it’s a nil
object or not; so 2 lines, instead of 4 (or more if you have to keep going deeper).
I have used try-except
before to catch the KeyError
, but this isn’t an approach I necessarily care for.
I’m not against external libraries, but due to the location of where the code is being run it’s extremely beneficial to stick to built-ins.