← Building with AI

Parsing JSON safely

Models sometimes reply with extra words. Do not crash.

Start this lesson

Even when you ask for JSON, a model can sometimes add a friendly sentence, leave a bracket off, or reply with something else. json.loads then raises an error and your whole program stops. Wrap the parse in try/except: if it fails, return None (or a clear message) so the rest of your program can decide what to do.

import json

def safe_parse(text):
    try:
        data = json.loads(text)
    except json.JSONDecodeError:
        return None
    return data

print(safe_parse('{"ok": true}'))         # {'ok': True}
print(safe_parse("Sure! Here you go..."))  # None

json.JSONDecodeError is the error json.loads raises for text that isn't valid JSON. (It is a kind of ValueError, so except ValueError also works.)

Valid JSON is not always the shape you wanted. '[1, 2]' parses fine but gives a list, not a dict. Checking the type with isinstance(data, dict) catches that.