Before code uses a model's reply, it must check that the reply has the expected shape.
What to build
A program that checks one reply against a tiny schema: an object with a string name and an integer age.
Requirements
- If the text is not JSON, print
invalid: not JSON. - If the JSON is not an object, print
invalid: not an object. - Check
namefirst, thenage: printinvalid: missing KEYif absent, orinvalid: KEY must be a stringorinvalid: KEY must be an integerif the type is wrong. - If everything is right, print
valid. A boolean is not an integer.
Input
One line with the reply.
Output
One line.
Constraints
The reply has at most 200 characters.
Example
Input:
{"name": "Ana", "age": 31}
Output:
valid
Why it works
Parsing catches text that is not JSON, and each later check removes one more way the reply could break the program, so the first failing check gives a precise reason.
Examples
Example 1 · Input
{"name": "Ana", "age": 31}
Expected output
valid
Example 2 · Input
Sure! {"name": "Ana"}
Expected output
invalid: not JSON
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
Wrap `json.loads` in `try` and catch `json.JSONDecodeError`.
Hint 2
Remember that `True` counts as an integer in Python, so test `bool` first or exclude it.
Solution
Show one correct solution (try it yourself first)
import json
text = input()
try:
data = json.loads(text)
except json.JSONDecodeError:
print("invalid: not JSON")
else:
if not isinstance(data, dict):
print("invalid: not an object")
elif "name" not in data:
print("invalid: missing name")
elif not isinstance(data["name"], str):
print("invalid: name must be a string")
elif "age" not in data:
print("invalid: missing age")
elif not isinstance(data["age"], int) or isinstance(data["age"], bool):
print("invalid: age must be an integer")
else:
print("valid")