Skip to main content

A model is asked to return JSON with a sentiment label and a score from 0 to 1 for a product review. Parse and validate the reply, and say what you do when it is malformed. For example, a reply wrapped in a code fence should parse, and a reply with sentiment "happy" should be rejected.

Coding rounds · Intermediate 2

Short answer

Treat the reply as untrusted input. Extract the JSON text, parse it with json.loads inside try and except, then validate keys, types and allowed values against a schema, for example with pydantic. On failure, retry a limited number of times with the error message, then fall back to a safe default and log it. Parsing is O(n) in reply length.

Deeper answer

First clarify the contract. Ask which fields are required, their types and allowed values, and what the caller needs when the reply is bad: an error, a default or a human review.

There are three steps. First, extract: models often add a code fence or a sentence, so take the text from the first { to the last } with re.search(r"\{.*\}", raw, re.DOTALL). No match is a failure too; a cut-off reply often has no closing brace. Second, parse with json.loads(text) and catch json.JSONDecodeError. Third, validate: sentiment is one of positive, negative or neutral, and score is a number with 0 <= score <= 1. A pydantic model does this in one call, Review.model_validate_json(text).

When any step fails, retry at most once or twice, sending the validation error back to the model, then return a fallback and log the raw reply. Test valid JSON, a fenced reply, a cut-off reply, a wrong label and a score given as text. By default pydantic converts the text "0.9" to a number; pass strict=True to reject it.

What a strong answer covers

Answer it out loud in the mock interview about 3 min

Follow-ups to expect

Common mistakes

Learn it

Files and errors

Practice Coding rounds questions

More on this topic

Today's AI turns are used

Lessons, roadmaps, videos, practice cards and the code playground stay free with your account, with no limit.