
Pull the JSON out of a reply
mediumPull the JSON out of a reply
OpenAI LLM Interview Question
A model asked for JSON often returns it wrapped in a sentence or a code fence. The calling code has to find the object before it can parse it.
Write a function extract_json(reply) that returns the first complete JSON object in the reply, parsed into a dictionary. Start at the first opening brace and track how deep you are until the braces balance. Return None when there is no complete object. Braces inside double-quoted strings do not count.
Asked of
- AI Engineer
- ML Engineer
- Data Scientist
Example 1
Input
reply = "Here you go: {\"name\": \"Ada\", \"age\": 36}. Let me know if that helps!"Output
{"name": "Ada", "age": 36}Example 2
Input
reply = "```json\n{\"ok\": true, \"items\": [1, 2]}\n```"Output
{"ok": True, "items": [1, 2]}Example 3
Input
reply = "I could not answer that."
Output
None
Explanation
In the first example the object starts after "Here you go:" and ends at the closing brace before the full stop. In the third there is no brace at all, so there is nothing to return.
Submit also runs 3 hidden test cases that check edge cases.
- Parsing
Similar questions
Company
OpenAI
Difficulty
medium
Topic
LLM
Language
Python
Your code
Loading Python in the background. You can start writing.