DEV Community

YoucefRabia
YoucefRabia

Posted on

I Built JSON.stringify and JSON.parse From Scratch in Vanilla JS — Here Are 5 Things That Broke My Brain

I hadn't coded in a year. I was a CRUD app maker, dropped out of software engineering, and spent the last few years studying something completely different. I came back to JS and bought some courses. Too slow. Too basic. I wanted to understand the tools I use every day, not just use them.

So I picked the most boring, most essential tool in JavaScript: JSON.stringify and JSON.parse.

The rule: If I can't build it, I don't understand it.


What I Built

A complete JSON engine in vanilla JavaScript:

  • Tokenizer — reads raw JSON text character by character and produces tokens
  • Parser — recursive descent parser that turns tokens into JS values
  • Serializer — turns JS values back into JSON text
  • Test suite — 107 tests covering every edge case I could find

Published to npm: @rabia_youcef/vanilla-json

Repo: github.com/MantasEdine/vanilla-json


5 Things That Broke My Brain

1. typeof null === "object"

The most famous bug in JavaScript. If your parser checks typeof input === "object" before checking input === null, you will crash trying to call Object.keys(null). Every single time.

2. JSON.stringify(NaN) returns "null"

Not "NaN". Not undefined. The string "null". Because the JSON spec says so.

3. undefined behaves differently in arrays vs objects

In an array: [1, undefined, 3]"[1,null,3]"

In an object: {a: 1, b: undefined}{"a":1}

The key just vanishes. The spec treats them differently and you have to handle both paths.

4. One \" inside a string destroys your tokenizer

If your string reader stops at the first " it sees, "say \"hello\"" will break. You have to handle escaped quotes or your parser dies on any real JSON.

5. 0 and -0 are different in IEEE 754

But JSON.stringify(-0) returns "0". JavaScript pretends they're the same for JSON purposes. I only found this because I was testing every number edge case I could think of.


Why This Project Is Perfect for Learning

You don't need frameworks. You don't need libraries. You need:

  • typeof
  • A for loop
  • A switch statement
  • Array.isArray
  • Object.keys

That's it. And you will touch recursion, closures, type coercion, memory management (WeakSet for circular refs), and the event loop (if you build the playground).


The Tutorial

I wrote the whole thing up as a step-by-step tutorial while I was building it. From "what is a token" to "why does circular reference detection need a WeakSet."

Read it here: vanille-json-docs.netlify.app

If you're tired of surface-level JavaScript tutorials and want to understand how the engine actually works, this is for you.

Top comments (0)