CPCODELAB
Node.js

Working with JSON

7 min read

Working with JSON

JSON is the lingua franca of Node.js APIs. The built-in JSON.stringify and JSON.parse methods handle serialisation and deserialisation. For reading JSON config files, you can require them directly in CommonJS.

js
// Parse JSON string to object
const jsonString = "{\"name\": \"Alice\", \"age\": 30}";
const user = JSON.parse(jsonString);
console.log(user.name); // Alice

// Stringify object to JSON
const product = { id: 1, name: "Widget", price: 9.99, tags: ["sale", "new"] };
const json = JSON.stringify(product, null, 2); // null = no replacer, 2 = indent
console.log(json);

Reading JSON Files

js
// CommonJS — require parses JSON automatically
const config = require("./config.json");
console.log(config.apiUrl);
js
// ESM or dynamic loading
const fs = require("fs/promises");

async function loadConfig() {
  const raw = await fs.readFile("./config.json", "utf8");
  const config = JSON.parse(raw);
  return config;
}

JSON.parse throws a SyntaxError on invalid input. Always wrap it in try/catch when parsing untrusted data (user input, file contents, API responses).

Ready to test yourself?
Practice Node.js— quiz & coding exercises