Streaming Partial JSON Parser for Strings and Arrays
Medium · Coding & Algorithms · Software Engineer · Technical Screen
Problem Statement
A real-time backend streams a JSON payload character by character over the network, and the frontend needs to materialize whatever data has arrived so far without waiting for the final byte. Implement def parse_partial_json(text: str) -> str | list: to convert an arbitrary non-empty prefix text of a valid JSON document—composed solely of strings and possibly nested arrays—into the corresponding Python str or list with all unfinished constructs cleanly closed.
No JSON objects, numbers, booleans, or null tokens ever occur in the stream. Your parser must follow these exact prefix rules:
- Represent every JSON array as a Python
listand every JSON string as a Pythonstr, preserving their order of appearance. - Once an opening quote
"arrives, that string is included in the output holding all characters received after it so far; iftextcuts off immediately after an opening", include the empty string"". - Every array whose
[has arrived without its closing]is closed automatically at the end oftext(cutting off right after[produces[]). - A comma
,(and any trailing spaces after it) with no subsequent element started yet contributes no element to its enclosing array. - The root value itself may be a bare string (
textstarting with", e.g.,'"cat'returns"cat") rather than an array. - When
textis already a complete JSON string or array, return its parsed value unchanged.
Examples
Example 1
Input: text = '["north", ["ea'
Output: ["north", ["ea"]]
Walk-through: "north" is complete, while the nested subarray cuts off mid-string after "ea, closing the partial string as "ea" and closing both open arrays around it.
Example 2
Input: text = '[["p", "q"], "r", '
Output: [["p", "q"], "r"]
Walk-through: After "r", the prefix terminates following a comma and two spaces before any third outer element begins, so no extra element is appended.
Example 3
Input: text = '[[""], [], ["'
Output: [[""], [], [""]]
Walk-through: The first inner array holds a completed empty string, the second inner array is closed and empty, and the third cuts off right after an opening quote—producing "" inside that closed inner array.
Constraints
1 <= len(text) <= 10^5text[0]is either'['or'"'.- Every character inside a string literal is printable ASCII (character codes
32to126) excluding'"'and'\\'(no escape sequences exist, though'[',']',',', and spaces may appear literally inside quotes). - Outside string literals, only
'[',']',',','"', and' '(space) appear. - Arrays are nested to a depth of at most
500.
Step-by-step walkthrough
Understand every truncation rule
When a backend streams JSON character by character, we receive a prefix
textthat can stop anywhere inside a JSON payload made of strings and nested arrays (with no escape sequences). We must return the Pythonstrorlistmaterialized so far, closing off anything still open:Where text stops | Expected behavior | Example ----------------------------------+---------------------------------+------------------------------- Mid-string | Keep characters received so far | '["ea' -> ["ea"] Right after an opening quote '"' | Include an empty string "" | '[[""], [], ["'-> [[""], [], [""]] Right after an opening '[' | Close as an empty list [] | '[[[' -> [[[]]] Right after ',' (and any spaces) | Add no extra element | '["r", ' -> ["r"] Top-level string (cut or full) | Return a str, not a list | '"cat' -> "cat" Complete JSON value | Return unchanged | '["a", []]' -> ["a", []]Watch out for one crucial detail in the constraints: inside a string, printable characters like
[,],,, and spaces are ordinary text, not JSON brackets or separators!Why naive string patching is tricky
Calling
json.loads(text)directly raisesJSONDecodeErrorwhenevertextis incomplete. You can repairtextinto valid JSON (append"if inside a string, strip trailing spaces and,, then append]for every unclosed[) and pass it tojson.loads, which makes a handy test oracle.However, to count unclosed
[brackets accurately, you already have to scantextwhile tracking whether each character sits inside quotes or outside quotes (so"a[b"does not fool your bracket count). Once you write that character scan, building the Python lists and strings directly takes just ~25 lines of clean code with zero trailing-comma string surgery!Key idea: two-mode state machine + stack of live lists
Scan
textonce from left to right with two modes: 1. Inside a string (in_string == True): Every character—including[,], and,—is ignored until the closing"arrives, at which point we slicetext[string_start:i]and append it to the current innermost list. 2. Outside a string (in_string == False): -"switchesin_stringtoTrueand recordsstring_start = i + 1. -[creates a new Python list, appends it to its parent immediately, and pushes it ontoopen_arrays. -]pops the finished innermost list offopen_arrays. -,and' 'do nothing at all!Look at why attaching a new list on
[(instead of waiting for]) makes unclosed arrays effortless:Because Python lists hold references: parent_list.append(new_array) # parent already points to new_array! open_arrays.append(new_array) # future items go into new_array If the stream suddenly cuts off before ']' ever arrives, new_array is ALREADY inside parent_list with all of its elements intact—nothing to unwind!And because we only append values when
[or"is seen (never on,), a trailing comma at the end oftextautomatically adds nothing!Unify top-level strings and arrays with a dummy wrapper
The top-level value might be a list (
'["a"' -> ["a"]) or a bare string ('"cat'->"cat"). Instead of writingif/elsebranches for the root, startopen_arrayswith a dummy wrapper listroot_holder = []:Initial state: root_holder = [] open_arrays = [root_holder] Case A: text = '"cat' End-of-stream appends "cat" into open_arrays[-1] (root_holder) root_holder == ["cat"] --> return root_holder[0] == "cat" Case B: text = '["a"' '[' creates list A, appends A into root_holder, pushes A End-of-stream appends "a" into open_arrays[-1] (A) root_holder == [["a"]] --> return root_holder[0] == ["a"]Because
textis a valid prefix starting with[or",]never popsroot_holder, androot_holder[0]always holds the exact top-level result.Code the character-by-character scan and end-of-stream flush
After the
forloop finishes, unclosed arrays are already attached in place. The only unfinished item not yet appended is a half-received string (in_string == True): appendingtext[string_start:]captures whatever arrived—and whentextended right after an opening",string_start == len(text)cleanly produces""!from typing import Any, List def parse_partial_json(text: str) -> str | list: """Parse a possibly truncated JSON prefix of strings and nested arrays.""" root_holder: List[Any] = [] open_arrays: List[list] = [root_holder] in_string = False string_start = 0 for i, ch in enumerate(text): if in_string: if ch == '"': open_arrays[-1].append(text[string_start:i]) in_string = False elif ch == '"': in_string = True string_start = i + 1 elif ch == "[": new_array: List[Any] = [] open_arrays[-1].append(new_array) open_arrays.append(new_array) elif ch == "]": open_arrays.pop() if in_string: open_arrays[-1].append(text[string_start:]) return root_holder[0]Trace Example 1 and Example 3 step by step
Example 1: text = '["north", ["ea' (length 14) i=0 '[' -> create A=[], root_holder=[A], open_arrays=[root, A] i=1 '"' -> in_string=True, string_start=2 i=2..6 -> 'n','o','r','t','h' skipped while in_string=True i=7 '"' -> append text[2:7]="north" to A; in_string=False; A=["north"] i=8,9 ', ' -> ignored outside string i=10 '[' -> create B=[], append to A -> A=["north", B], open_arrays=[root, A, B] i=11 '"' -> in_string=True, string_start=12 i=12,13 -> 'e','a' skipped while in_string=True End of text: in_string is True -> append text[12:]="ea" to B! Return root_holder[0] -> ["north", ["ea"]] Example 3: text = '[[""], [], ["' (length 13) i=0 '[' -> create outer=[], root_holder=[outer] i=1 '[' -> create inner1=[], outer=[inner1] i=2,3 '""' -> append text[3:3]="" to inner1 -> inner1=[""] i=4 ']' -> pop inner1; outer=[[""]] i=5,6 ', ' -> ignored i=7,8 '[]' -> create & pop inner2=[]; outer=[[""], []] i=9,10 ', '-> ignored i=11 '[' -> create inner3=[], outer=[[""], [], inner3] i=12 '"' -> in_string=True, string_start=13 End of text: in_string is True -> append text[13:]="" to inner3! Return root_holder[0] -> [[""], [], [""]]Plan a thorough edge-case test suite
Group your edge-case tests systematically by truncation boundary and structural traps: - Every truncation point: mid-string (
'["ea'), immediately after opening quote ('"'and'[[""], [], ["'), immediately after[('['and'[[['), after,with and without trailing spaces ('["a",','["r", '), and right after an inner]closes ('[["p"]'). - Top-level shapes & complete values: bare top-level strings ('"cat','"done"') and complete nested structures ('[["a"], [], ""]'). - Trap characters inside strings: brackets and commas inside quotes ('["a[b", "c, d]", "]'). - Scale & fuzzing: 500 levels of nested[brackets (verifying no recursion-limit crash),10^5-character strings (verifying linear slicing speed), and checking every prefixtext[:cut]of randomly generated nested arrays against a patch-and-json.loadsreference.Complete solution
from typing import Any, Dict, List, Optional, Set, Tuple def parse_partial_json(text: str) -> str | list: """Parse a possibly truncated JSON prefix of strings and nested arrays.""" # root_holder: dummy 1-element wrapper list so top-level strings ('"cat') and # top-level arrays ('["a"') append their value to open_arrays[-1] identically. root_holder: List[Any] = [] # open_arrays: stack of currently open lists; open_arrays[-1] is the innermost active list. open_arrays: List[list] = [root_holder] # in_string: True while scanning between an opening '"' and its closing '"'. in_string = False # string_start: index of the first character right after the opening '"'. string_start = 0 for i, ch in enumerate(text): if in_string: if ch == '"': # Closing quote arrived: slice once in O(length) and append to current array. open_arrays[-1].append(text[string_start:i]) in_string = False # Any other character inside quotes (even '[', ']', or ',') is literal text. elif ch == '"': # Opening quote: enter string mode; characters start at the next index. in_string = True string_start = i + 1 elif ch == "[": # Attach new_array to its parent IMMEDIATELY upon '[' (not on ']'): # Python stores a list reference, so if the stream cuts off before ']', # the array and everything inside it are already linked into the parent! new_array: List[Any] = [] open_arrays[-1].append(new_array) open_arrays.append(new_array) elif ch == "]": # Finished the innermost array; pop back to its parent array. open_arrays.pop() # Commas and spaces outside strings are skipped: values attach when they open/close, # which guarantees a trailing comma adds nothing to its array. # Post-scan flush: if the stream cut off mid-string, keep whatever characters arrived # (if text ended right after '"', string_start == len(text) and this appends ""). if in_string: open_arrays[-1].append(text[string_start:]) return root_holder[0]✅ Submit now — all tests should pass.
Intuition & how it works
Imagine assembling nested gift boxes while listening to live instructions over a walkie-talkie that could cut out at any second. You keep a stack (a last-in, first-out list of open boxes where the innermost box sits on top) and a state machine (a loop whose behavior depends on a small mode flag, in_string):
- When you hear [, you grab a brand-new box, place it inside the current box immediately (by storing a shared reference, so both the parent box and the stack point to the exact same Python list), and step inside it.
- When you hear ], you step back out to the parent box.
- When you hear ", you toggle "dictation mode" (in_string), where every character—even [ or ,—is just plain label text until the closing " arrives.
Because every box is linked into its parent the instant it opens, if the signal dies mid-stream, every open box is already nested in place and you only need to save any half-dictated string! Starting the stack with a sentinel container (root_holder = [], a dummy outer wrapper list) lets a bare top-level string and a top-level array use the exact same code.
Passing a truncated prefix (an incomplete beginning of a message) straight to json.loads fails immediately with a syntax error. Trying to split on , or count [ minus ] without tracking quotes also fails as soon as a string itself contains brackets or commas like '["a, [b", "c'. Scanning once with in_string and open_arrays handles quotes, nesting, and arbitrary cutoffs in one clean pass.
Trace '["hi", ["ok' (11 characters):
- [ opens outer list A inside root_holder -> open_arrays = [root_holder, A].
- "hi" toggles in_string on at index 1 and off at index 4, slicing "hi" into A -> A = ["hi"].
- , and ' ' outside quotes are ignored.
- [ opens inner list B, appends B into A right away (A = ["hi", []]), and pushes B.
- "ok opens a string at string_start = 9 before text ends; the post-loop check if in_string: appends text[9:] = "ok" into B, returning ["hi", ["ok"]].
Complexity
- Time —
O(n): We scan each of thencharacters intextonce, doingO(1)list push/pop work at brackets and copying each string character at most once when slicingtext[string_start:i]ortext[string_start:]. - Space —
O(n): The returned structure stores at mostncharacters and list elements, andopen_arraysholds at mostdepth + 1references (at most501entries for nesting depth500).
Edge cases
- Cutoff right after an opening quote (
'"'or'[[""], [], ["'):in_stringisTruewithstring_start == len(text), sotext[string_start:]evaluates to""and appends an empty string element as required. - Cutoff right after
[('['or'[[['): Eachnew_arraywas already appended to its parent upon[, returning[]or[[[]]]with no extra cleanup. - Cutoff after a comma and spaces (
'[["p", "q"], "r", '): Commas and spaces outside quotes never create placeholder elements, returning[["p", "q"], "r"]. - Top-level string (
'"cat','"','"done"'): Appended directly intoroot_holder[0]and returned as astr, not wrapped in an extra list. - Structural characters inside strings (
'["a[b", "c, d]", "]'): Whilein_stringisTrue, only"triggers an action, so[,], and,stay literal characters. - Deep nesting (
500open[brackets): Handled on the explicitopen_arrayslist without touching Python's call stack.
Common mistakes
- Treating
[,], or,inside quotes as JSON structure: Always checkif in_string:first in the loop so'["a]", "b'does not popopen_arraysprematurely. - Waiting until
]to append a child array to its parent: Any array whose closing]was cut off would be stranded onopen_arraysunless you wrote a second loop to pop and stitch them together. - Appending an element whenever
,is seen: Leaves a phantom""orNoneat the end whenever the stream pauses after a trailing comma. - Concatenating characters one by one (
cur += ch) inside strings: Repeated string concatenation can degrade toO(n^2)in languages with immutable strings (or non-CPython runtimes); recordingstring_startand slicing once is guaranteedO(length). - Using a recursive-descent parser (mutually recursive functions like
parse_value()->parse_array()->parse_value()) without checking stack depth: Two stack frames per nesting level across 500 nested arrays hits Python's default 1,000-frame recursion limit (RecursionError).
Alternative approaches
- Close off the raw JSON text and call
json.loads: Scantext(or split on"since there are no escapes: even-indexed segments lie outside strings, odd-indexed segments lie inside strings!) to check if quote count is odd (append") or strip trailing spaces and,, count net open[minus]in outside-string segments, append"]" * depth, and calljson.loads. This runs inO(n)time and serves as a great randomized-test cross-check, though direct stack construction avoids allocating a patched string and re-parsing from scratch.
Follow-up questions
- How would you redesign the parser into an incremental streaming class so each incoming chunk updates the state in O(chunk_length) time without rescanning earlier text? Turn the scanner into a stateful class storing
root_holder,open_arrays,in_string, and achar_buffer: List[str]for any in-progress string. Whenever"opens a string, append""intoopen_arrays[-1]right away as a live slot and updateopen_arrays[-1][-1] = "".join(char_buffer)at the end of eachfeed(chunk)call while the string remains open, achievingO(chunk_length)incremental updates (or copy on read if callers require immutable snapshots). - What changes are needed if strings may contain JSON escape sequences such as \", \, \n, and \uXXXX? Because slices of raw
textno longer match the decoded characters, collect decoded characters into achars: List[str]buffer whilein_stringisTrueand add anescape_modestate (None,"backslash", or"unicode_hex"collecting 4 hex digits). If the stream cuts off mid-escape (such as trailing\or\u00), withhold the incomplete escape sequence until its remaining bytes arrive so the UI never displays a garbled character or stray backslash. - How would you extend your state machine to support partial JSON objects, numbers, booleans, and null? Push tagged stack frames (for example,
("array", list_obj)vs("object", dict_obj, pending_key)) so:and,know whether the parser expects an object key or value. Decide clean UX rules for each new partial token: omit an object key until at least the start of its value arrives (or map it toNone), hide partial literals liketrornuuntil complete (true/null), and carefully handle partial numbers like-or3.(either holding back numbers until a delimiter proves they are complete, or parsing valid numeric prefixes while guarding bare-).
Follow-up questions
- How would you redesign the parser into an incremental streaming class so each incoming chunk updates the state in O(chunk_length) time without rescanning earlier text?
- What changes are needed if strings may contain JSON escape sequences such as \", \\, \n, and \uXXXX?
- How would you extend your state machine to support partial JSON objects, numbers, booleans, and null?
Similar questions
- Recover Nested Pick-List From Truncated Stream
- 2D Max Pooling with Source Coordinates
- Time-Limited Credit Ledger
- Grid Path Scoring with Streak Bonuses
- Place One Hub to Minimize Maximum Grid Distance
- Increment Fixed-Size Digit Array by One