medium +14 pts

Extract JSON-like numbers

Parse a simplified JSON-like string and sum all numeric values, ignoring numbers inside strings.

Write a function `extract_json_numbers(s: str) -> float` that parses a **JSON-like** string `s` containing a single object or array structure and returns the sum of all numbers present. The string will be well-formed and may include: - Objects: `{ "key": value, ... }` with string keys. - Arrays: `[value1, value2, ...]`. - Strings: enclosed in double quotes, may contain escaped quotes `\"` and backslashes `\\`. - Numbers: integers (e.g., `0`, `-5`) and decimals (e.g., `3.14`, `-0.5`). Do not include numbers inside strings. Ignore booleans and null. You must **not** use the `json` module or any other external parser. Implement your own parser using string processing, recursion, or a simple state machine. The input is guaranteed to be valid and non-empty. Return the sum of all numbers in the structure as a number (integer or float). If no numbers exist, return 0.

Constraints

The length of `s` is between 1 and 10,000. Numbers will be valid JSON numbers (integer or decimal). The sum of all absolute values will fit in a Python float. Input is guaranteed well-formed, so you do not need to handle malformed JSON.

Example

```python
>>> extract_json_numbers('{"a": 1, "b": 2.5, "c": [3, -4]}')
2.5
>>> extract_json_numbers('[10, "20", 30]')
40
>>> extract_json_numbers('{"a": "1,2", "b": 0}')
0
```
14 points ~20 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

You can traverse the string character by character, keeping a current state (e.g., inside a string, inside a number, etc.).
When you encounter a digit or '-' outside a string, parse the full number token and add it to the sum.
Use a flag to track whether you are inside a string to avoid counting digits in string values.
Remember to handle escaped quotes within strings.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.