typestar

JSON in JavaScript

Serializing and parsing, with error handling.

const profile = { name: "ada", langs: ["js", "rust"], active: true };

const text = JSON.stringify(profile, null, 2);
const compact = JSON.stringify(profile);
const restored = JSON.parse(text);

function safeParse(input) {
  try {
    return { ok: true, value: JSON.parse(input) };
  } catch (error) {
    return { ok: false, error: error.message };
  }
}

How it works

  1. stringify takes indentation as its third argument.
  2. parse throws on malformed input.
  3. Wrapping it returns a result object instead.

Keywords and builtins used here

The run, in numbers

Lines
13
Characters to type
341
Tokens
100
Three-star pace
95 tpm

At the three-star pace of 95 tokens a minute, this run takes about 63 seconds.

Type this snippet

Step 1 of 3 in Data formats, step 40 of 43 in Language basics.

← Previous Next →