Emmanuel Akinfulubi

JavaScriptFundamental (ES6), part 2

Write a JSON parser in JavaScript

116 A JSON parser by hand, checked against the real one

hard

Write a JSON parser: objects, arrays, strings with all six short escapes and \uXXXX, numbers, and the three literals. Then hold it to the only standard that matters by comparing every result with JSON.parse on the same text — including the inputs both must reject, such as a trailing comma, a single-quoted string and NaN. Two behaviours are worth discovering rather than assuming: what happens to a duplicate key, and what happens when the key is __proto__.

Stuck? Three hints, smallest first
  1. 1. One index, one skipSpace, and one value() that dispatches on the current character. Every helper leaves the index just past what it consumed.
  2. 2. JSON numbers are narrower than JavaScript numbers: no leading +, no leading zeros, no bare .5, no NaN. Match the grammar with a regex anchored at your position and let Number do the conversion.
  3. 3. Assigning a parsed key with object[key] = value is a mistake for exactly one key. Use Object.defineProperty, and compare what the two versions do with __proto__.

The answer

const BACKSLASH = String.fromCharCode(92);   // written this way to keep the escaping readable
const SHORT = { '"': '"', '/': '/', b: '\b', f: '\f', n: '\n', r: '\r', t: '\t' };
SHORT[BACKSLASH] = BACKSLASH;
const NUMBER = /^-?(0|[1-9][0-9]*)(\.[0-9]+)?([eE][+-]?[0-9]+)?/;

function parseJson(text, { protoSafe = true } = {}) {
  let i = 0;

  const fail = (message) => {
    const err = new Error(message + ' at position ' + i);
    err.name = 'SyntaxError';
    err.position = i;
    throw err;
  };
  const skipSpace = () => {
    while (i < text.length && (text[i] === ' ' || text[i] === '\t' || text[i] === '\n' || text[i] === '\r')) i++;
  };
  const expect = (c) => { if (text[i] !== c) fail('expected ' + JSON.stringify(c)); i++; };

  const string = () => {
    expect('"');
    let out = '';
    for (;;) {
      if (i >= text.length) fail('unterminated string');
      const c = text[i];
      if (c === '"') { i++; return out; }
      if (c.charCodeAt(0) < 32) fail('raw control character in string');
      if (c !== BACKSLASH) { out += c; i++; continue; }
      i++;
      const kind = text[i];
      if (kind === 'u') {
        const hex = text.slice(i + 1, i + 5);
        if (!/^[0-9a-fA-F]{4}$/.test(hex)) fail('bad unicode escape');
        out += String.fromCharCode(parseInt(hex, 16));
        i += 5;
        continue;
      }
      if (!Object.prototype.hasOwnProperty.call(SHORT, kind)) fail('unknown escape');
      out += SHORT[kind];
      i++;
    }
  };

  const value = () => {
    skipSpace();
    const c = text[i];
    if (c === '{') {
      i++;
      const out = {};
      skipSpace();
      if (text[i] === '}') { i++; return out; }
      for (;;) {
        skipSpace();
        const key = string();
        skipSpace();
        expect(':');
        const parsed = value();
        if (protoSafe) {
          Object.defineProperty(out, key, { value: parsed, writable: true, enumerable: true, configurable: true });
        } else {
          out[key] = parsed;                 // wrong for exactly one key
        }
        skipSpace();
        if (text[i] === ',') { i++; continue; }
        expect('}');
        return out;
      }
    }
    if (c === '[') {
      i++;
      const out = [];
      skipSpace();
      if (text[i] === ']') { i++; return out; }
      for (;;) {
        out.push(value());
        skipSpace();
        if (text[i] === ',') { i++; continue; }
        expect(']');
        return out;
      }
    }
    if (c === '"') return string();
    if (text.startsWith('true', i)) { i += 4; return true; }
    if (text.startsWith('false', i)) { i += 5; return false; }
    if (text.startsWith('null', i)) { i += 4; return null; }
    const match = NUMBER.exec(text.slice(i));
    if (match) { i += match[0].length; return Number(match[0]); }
    return fail('unexpected ' + (i >= text.length ? 'end of input' : JSON.stringify(c)));
  };

  const out = value();
  skipSpace();
  if (i < text.length) fail('unexpected trailing ' + JSON.stringify(text[i]));
  return out;
}

const rejects = (fn) => { try { fn(); return false; } catch (err) { return true; } };
const errorOf = (fn) => { try { fn(); return 'no error'; } catch (err) { return err.message; } };

const receipt = '{ "till": "Balogun 1", "items": [ { "sku": "ADR-1", "kobo": 450000 }, ' +
  '{ "sku": "ADR-2", "kobo": 125000 } ], "paid": true, "void": false, "note": null, "vat": 7.5e-2 }';
const mine = parseJson(receipt);
const theirs = JSON.parse(receipt);
const matchesTheRealThing = [same(mine, theirs), mine.items[1].kobo, mine.vat, mine.note, mine.void];

// A string with every awkward escape in it, built without drowning in backslashes.
const escaped = '"Adaeze' + BACKSLASH + 'nsaid ' + BACKSLASH + '"eleven' + BACKSLASH + '" ' +
  BACKSLASH + 'u20a6450 ' + BACKSLASH + BACKSLASH + ' end"';
const decoded = parseJson(escaped);
const escapeBehaviour = [decoded === JSON.parse(escaped), decoded.split('\n').length, decoded.indexOf('\u20a6450') !== -1, decoded.indexOf(BACKSLASH) !== -1];

const numbers = '[0, -0.5, 12, 1e3, -2.5E+2, 1e-3]';
const numbersMatch = [same(parseJson(numbers), JSON.parse(numbers)), parseJson(numbers)];

const duplicated = '{"kobo": 100, "kobo": 250}';
const duplicateKeys = [parseJson(duplicated).kobo, JSON.parse(duplicated).kobo, Object.keys(parseJson(duplicated)).length];

const bad = ['{"a": 1,}', "{'a': 1}", '{"a": NaN}', '[01]', '[+1]', '[.5]', '{"a": 1} extra', '', '   ', '[1, 2'];
const bothReject = bad.map((text) => [rejects(() => parseJson(text)), rejects(() => JSON.parse(text))]);
const everyOneRejectedByBoth = bothReject.every(([a, b]) => a === true && b === true);

const positioned = errorOf(() => parseJson('{"a": 1, "b": tru}'));

const polluting = '{"__proto__": {"admin": true}, "user": "Adaeze"}';
const safe = parseJson(polluting);
const naive = parseJson(polluting, { protoSafe: false });
const real = JSON.parse(polluting);
const protoStory = [
  Object.keys(safe),
  Object.keys(naive),
  same(Object.keys(safe), Object.keys(real)),
  naive.admin === true,
  safe.admin,
];

const huge = '{"n": 9007199254740993}';
const precisionLoss = [parseJson(huge).n === JSON.parse(huge).n, parseJson(huge).n === 9007199254740992];

console.log('receipt matches :', matchesTheRealThing);
console.log('escapes         :', JSON.stringify(decoded));
console.log('bad input       :', everyOneRejectedByBoth, 'for', bad.length, 'inputs');
console.log('__proto__       :', protoStory);

Output


      
8 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 8 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

8 checks

test('a whole receipt parses to exactly what JSON.parse produces', matchesTheRealThing, [true, 125000, 0.075, null, false]);
test('every short escape and a \\u escape decode the same way the real parser decodes them', escapeBehaviour, [true, 2, true, true]);
test('the number grammar handles fractions and exponents identically', numbersMatch, [true, [0, -0.5, 12, 1000, -250, 0.001]]);
test('a duplicate key is not an error: the last one wins, in both parsers', duplicateKeys, [250, 250, 1]);
test('all ten malformed inputs are rejected, and rejected by JSON.parse too', [everyOneRejectedByBoth, bothReject.length], [true, 10]);
test('an error says what it choked on and where', positioned, 'unexpected "t" at position 14');
test('__proto__ must be defined, not assigned, or the key vanishes into the prototype', protoStory, [['__proto__', 'user'], ['user'], true, true, undefined]);
test('and a 17-digit integer loses precision in exactly the same way', precisionLoss, [true, true]);

The __proto__ assertion is the one to take away. out[key] = parsed looks like the obvious way to build an object, and for one key in the language it does something else entirely: assigning to __proto__ invokes the inherited setter and changes the object's prototype instead of creating a property. The naive parse loses the key from Object.keys and gains an inherited admin that reads as true — that is prototype pollution, and it is a real vulnerability class, not a curiosity. Object.defineProperty defines an own property and matches what JSON.parse does, which is why the real parser is safe here while a hand-rolled one often is not.

JSON's number grammar is narrower than JavaScript's, and that is the second thing people get wrong by reaching for parseFloat. 01, +1, .5, 1., Infinity and NaN are all illegal JSON, and parseFloat happily accepts most of them — worse, it accepts a valid prefix of an invalid token and reports no error. An anchored regex that matches the grammar and nothing else, with Number for the conversion, is the honest version.

Two shared behaviours are worth knowing rather than guessing. A duplicate key is not an error in JSON: the specification permits it and every mainstream parser keeps the last one, so a document with two kobo keys is accepted and one value silently disappears. And 9007199254740993 parses to 9007199254740992, because JSON has no integer type and the value goes through a double; an API returning 64-bit identifiers as numbers is corrupting them before your code ever sees them, which is why those identifiers arrive as strings in any API that has been bitten.

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.