Step 1 : Load your JSON as a dict
import json
my_json_dict = json.loads(json_string)
The json
library parses your JSON string to a Python dictionary.
Step 2 : Access the value using key
value1 = my_json_dict['ID']
value1 = my_json_dict.get('ID', default_value) # Preferred.
The first statement will throw an exception if KEY1
is not available in the JSON string.
The second statement is safer, as a fallback value can be given.
Step 3 : Apply your business logic
if id == 1:
# do your operations.
If you must use the first line, or if dealing with unknowns that could throw errors anyway, test for the error you are getting and add exception handling around in it as in:
try:
<your code solution here>
except NameOfError as ee:
<what to do if error occurs>
print(type(ee)); print(ee) # if you want to see the error
You can add as many except statements as there are error types you are attempting to process. A generic "Exception" can be used in place of NameOfError as a catch-all for unknown errors, but best practice is to handle the true Exceptions first by type. A little testing as code breaks initially can reveal what should go in place of "NameOfError".