Working with JSON

View saved

Parse and stringify

JSON is text. Convert to objects to work with data, then stringify to send or save.

const raw = '{"name":"Ada","lessons":3}';
const data = JSON.parse(raw);
console.log(data.name);

const text = JSON.stringify(data, null, 2);
console.log(text);

Read JSON from disk

Common config pattern:

import { readFile } from "fs/promises";

const config = JSON.parse(await readFile("config.json", "utf8"));
console.log(config);

Send JSON from Express

res.json sets the Content-Type and stringifies for you.

res.status(200).json({ ok: true, items });

Handle bad JSON

Wrap JSON.parse in try/catch—malformed text throws a SyntaxError.

try {
  JSON.parse(bodyText);
} catch {
  // respond 400 in an HTTP handler
}

Comments

One comment per signed-in account. Comments are saved with this page’s URL.