On this page

Project: A Recursive-Descent JSON Parser Using Result/Option Idioms Throughout

Published on August 8, 2026

Enrico Hochkoeppler Profile

By Enrico Hochkoeppler

Web Developer & TutoriaLibre Founder

This project builds a complete JSON parser — tokenizer, recursive-descent grammar, and top-level entry point — using Result and let* as the only error-handling mechanism from beginning to end. No exception is ever raised or caught anywhere in the parsing logic; every function that can fail says so directly in its return type, and every failure propagates automatically through let* rather than through unwinding a stack.

The Problem, Stated Precisely​

Build a function parse : string -> (json, string) result that:

For example:


parse {|{"name": "Ada", "active": true, "scores": [1, 2, 3]}|}

(* Ok (Assoc [("name", String "Ada"); ("active", Bool true);

             ("scores", List [Number 1.; Number 2.; Number 3.])]) *)



parse {|{"broken": }|}

(* Error "unexpected token, expected a value" *)

Step 1: Set Up the Project​


dune init proj jsonparser

cd jsonparser

The implementation lives in bin/main.ml for this project, since the goal here is the parsing logic itself rather than a reusable library.

Step 2: Define the JSON Value Type​

A JSON value is one of six alternatives, two of which — arrays and objects — contain further JSON values, making this a recursive variant type:


type json =

  | Null

  | Bool of bool

  | Number of float

  | String of string

  | List of json list

  | Assoc of (string * json) list

Assoc represents a JSON object as an association list of string keys to json values, and List represents a JSON array the same way lists have been represented throughout — both are ordinary recursive uses of json inside its own definition, exactly like a tree's branches referring back to the tree type itself.

Step 3: Bring let* Into Scope for Result​

Every parsing function in this project chains together through Result.bind, aliased to the let* binding operator for readability:


let ( let* ) = Result.bind

With this in place, let* x = expr in ... runs ... with x bound to expr's contents only if expr is Ok; if expr is Error, the entire surrounding function immediately evaluates to that same Error, with nothing after it ever running.

Step 4: Define the Token Type​

Tokenizing turns raw characters into a flat sequence of meaningful pieces, exactly as with the arithmetic expression evaluator built earlier in this course, just with a token set matching JSON's grammar instead:


type token =

  | LBRACE

  | RBRACE

  | LBRACKET

  | RBRACKET

  | COLON

  | COMMA

  | TSTRING of string

  | TNUMBER of float

  | TBOOL of bool

  | TNULL

Step 5: Write the Tokenizer​

The tokenizer walks a character list, skipping whitespace, recognizing structural characters directly, and delegating strings and numbers to two small helpers:


let explode s = List.init (String.length s) (String.get s)



let is_digit c = c >= '0' && c <= '9'



let rec read_string chars =

  let rec go acc = function

    | '"' :: rest -> Ok (acc, rest)

    | '\\' :: 'n' :: rest -> go (acc ^ "\n") rest

    | '\\' :: 't' :: rest -> go (acc ^ "\t") rest

    | '\\' :: '"' :: rest -> go (acc ^ "\"") rest

    | '\\' :: '\\' :: rest -> go (acc ^ "\\") rest

    | c :: rest -> go (acc ^ String.make 1 c) rest

    | [] -> Error "unterminated string"

  in

  go "" chars



let read_number chars =

  let rec go acc = function

    | c :: rest when is_digit c || c = '-' || c = '.' || c = 'e' || c = 'E' || c = '+' ->

      go (acc ^ String.make 1 c) rest

    | rest -> (acc, rest)

  in

  go "" chars



let rec tokenize chars =

  match chars with

  | [] -> Ok []

  | (' ' | '\n' | '\t' | '\r') :: rest -> tokenize rest

  | '{' :: rest -> Result.map (fun ts -> LBRACE :: ts) (tokenize rest)

  | '}' :: rest -> Result.map (fun ts -> RBRACE :: ts) (tokenize rest)

  | '[' :: rest -> Result.map (fun ts -> LBRACKET :: ts) (tokenize rest)

  | ']' :: rest -> Result.map (fun ts -> RBRACKET :: ts) (tokenize rest)

  | ':' :: rest -> Result.map (fun ts -> COLON :: ts) (tokenize rest)

  | ',' :: rest -> Result.map (fun ts -> COMMA :: ts) (tokenize rest)

  | '"' :: rest ->

    let* s, rest' = read_string rest in

    let* ts = tokenize rest' in

    Ok (TSTRING s :: ts)

  | 't' :: 'r' :: 'u' :: 'e' :: rest -> Result.map (fun ts -> TBOOL true :: ts) (tokenize rest)

  | 'f' :: 'a' :: 'l' :: 's' :: 'e' :: rest -> Result.map (fun ts -> TBOOL false :: ts) (tokenize rest)

  | 'n' :: 'u' :: 'l' :: 'l' :: rest -> Result.map (fun ts -> TNULL :: ts) (tokenize rest)

  | c :: _ when is_digit c || c = '-' ->

    let num_str, rest' = read_number chars in

    (match float_of_string_opt num_str with

     | Some n ->

       let* ts = tokenize rest' in

       Ok (TNUMBER n :: ts)

     | None -> Error (Printf.sprintf "invalid number: %s" num_str))

  | c :: _ -> Error (Printf.sprintf "unexpected character '%c'" c)

read_string accumulates characters until an unescaped closing quote, handling the four most common escape sequences directly and reporting Error "unterminated string" if the input runs out first. read_number greedily collects every character that could plausibly belong to a JSON number; tokenize then hands that collected string to float_of_string_opt, converting a None result into a descriptive Error rather than letting a malformed number silently become 0. or crash the program. Every recursive branch of tokenize itself either uses Result.map to prepend a simple token onto the rest of the tokenized result, or let* to chain a multi-step case like strings and numbers, propagating any failure automatically rather than needing an explicit check at every single step.

Step 6: Write the Recursive-Descent Parser​

With a token list in hand, parse_value and its mutually recursive helpers walk that list directly, each returning both a parsed piece and whatever tokens remain after it:


let rec parse_value tokens =

  match tokens with

  | TNULL :: rest -> Ok (Null, rest)

  | TBOOL b :: rest -> Ok (Bool b, rest)

  | TNUMBER n :: rest -> Ok (Number n, rest)

  | TSTRING s :: rest -> Ok (String s, rest)

  | LBRACKET :: rest -> parse_array rest

  | LBRACE :: rest -> parse_object rest

  | [] -> Error "unexpected end of input, expected a value"

  | _ -> Error "unexpected token, expected a value"



and parse_array tokens =

  match tokens with

  | RBRACKET :: rest -> Ok (List [], rest)

  | _ ->

    let* items, rest = parse_elements tokens in

    Ok (List items, rest)



and parse_elements tokens =

  let* v, rest = parse_value tokens in

  match rest with

  | COMMA :: rest' ->

    let* items, rest'' = parse_elements rest' in

    Ok (v :: items, rest'')

  | RBRACKET :: rest' -> Ok ([ v ], rest')

  | _ -> Error "expected ',' or ']' in array"



and parse_object tokens =

  match tokens with

  | RBRACE :: rest -> Ok (Assoc [], rest)

  | _ ->

    let* members, rest = parse_members tokens in

    Ok (Assoc members, rest)



and parse_members tokens =

  match tokens with

  | TSTRING key :: COLON :: rest ->

    let* v, rest' = parse_value rest in

    (match rest' with

     | COMMA :: rest'' ->

       let* members, rest''' = parse_members rest'' in

       Ok ((key, v) :: members, rest''')

     | RBRACE :: rest'' -> Ok ([ (key, v) ], rest'')

     | _ -> Error "expected ',' or '}' in object")

  | _ -> Error "expected a string key in object"

parse_value is the entry point for any single JSON value, dispatching on the first token; LBRACKET and LBRACE hand off to parse_array and parse_object, which check for the immediate empty case before delegating to parse_elements and parse_members for the general case of one or more items separated by commas. Every one of these functions returns a (result_piece * token list) result pair — the parsed value or structure, together with whatever tokens are left over — and every step that depends on a previous step's success uses let* to thread both the value and the remaining tokens forward, with a malformed input anywhere in the chain short-circuiting the entire parse immediately.

Step 7: Assemble the Top-Level parse Function​


let parse s =

  let* tokens = tokenize (explode s) in

  let* value, remaining = parse_value tokens in

  match remaining with

  | [] -> Ok value

  | _ -> Error "unexpected trailing tokens"

parse chains the tokenizer into the parser using the exact same let* mechanism used throughout every layer beneath it, and adds one final check of its own: a completely valid JSON value must consume every token, so anything left over afterward is reported as an error rather than silently ignored.

Step 8: Test It​


# parse {|null|};;

- : (json, string) result = Ok Null



# parse {|[1, 2, 3]|};;

- : (json, string) result = Ok (List [Number 1.; Number 2.; Number 3.])



# parse {|{"name": "Ada", "active": true}|};;

- : (json, string) result =

Ok (Assoc [("name", String "Ada"); ("active", Bool true)])



# parse {|{"broken": }|};;

- : (json, string) result = Error "unexpected token, expected a value"



# parse {|[1, 2,|};;

- : (json, string) result = Error "unexpected end of input, expected a value"



# parse {|42 43|};;

- : (json, string) result = Error "unexpected trailing tokens"

Each of these checks a distinct layer of the parser: the first three confirm nested structures parse correctly end to end, and the last three confirm that a missing value, a truncated array, and trailing input after a complete value each produce a specific, distinguishable error message rather than a generic failure or a crash.

Extending the Project​

A few natural next steps:

Found this helpful? Share the knowledge...

... or support this project to keep it alive!

Buy Me a Coffee

Previous

Lazy Evaluation & Streamed Data

Next

Advanced Type System