The first recursive structure
Parse empty, nested and heterogeneous arrays.
The project contract
Your program must read one JSON document from standard input. If it is valid, write that same value to standard output serialized as compact JSON and exit with code 0. If it is not valid, write nothing to stdout, explain the error on stderr and exit with a code other than 0.
The tester runs, from the project root, the commands you declare in shipcode.yml:
challenge: json-parser
build: your-build-command # optional
run: your-run-command
Do not use your standard library's JSON parser, nor an equivalent dependency. You may use its data types and a serializer at the end: what you are building is the lexical and syntactic analysis.
Your goal
Add arrays. After [ there may come ] or a sequence of values separated by commas. Each element calls your general parse function again: that is where the recursion holding up the whole document shows up.
Avoid the permissive comma
Model the states "I expect a value" and "I expect a comma or a closing bracket" explicitly. That way you will naturally reject [1,], [,1] and [1 2]. Skip whitespace at every boundary, not inside tokens such as numbers.
Define a reasonable maximum depth too, or turn the overflow into a controlled error. The input comes from outside and should not be able to take the process down.
Recursion appears here
An array calls the same operation that already reads “one JSON value.” That operation can choose a literal, number, string, or another array. This is recursive descent: functions follow the shape of the grammar.
Consume [, handle the empty array first, otherwise require a value, and then require either a comma or ]. After a comma, require another value; this naturally rejects [1,].
Keep the states “expecting a value” and “expecting a separator or close” clear. Skip whitespace only between tokens. Add a reasonable nesting limit so hostile input becomes a controlled error instead of a process crash.
Never split the text on commas: nested structures contain commas too.
Before the tests
Try [], [1], mixed values, nested arrays, [1,], [,1], [1 2], and [1}.
Acceptance criteria
- Accepts the empty array, mixed values and nesting.
- Allows whitespace around values, commas and brackets.
- Rejects trailing commas, missing elements and wrong closers.
- Preserves the order of the elements.
Run shipcode test --stage 04-arrays.