Working with JSON

Convert between JSON text and JavaScript objects.

SyntaxJSON.parse(text) JSON.stringify(obj, null, 2)

JSON (JavaScript Object Notation) is the standard format for exchanging data between servers and clients. Node has built-in tools to convert it:

  • JSON.stringify(value) β€” object to JSON text.
  • JSON.parse(text) β€” JSON text back to an object.

Reading a JSON file

Read the file as text, then parse it. Writing is the reverse: stringify, then write.

Example

Example Β· javascript
const fs = require('fs/promises');

async function run() {
  const user = { name: 'Ada', roles: ['admin', 'user'] };
  const text = JSON.stringify(user, null, 2);
  await fs.writeFile('user.json', text);

  const loaded = JSON.parse(await fs.readFile('user.json', 'utf8'));
  console.log(loaded.roles[0]); // admin
}
run();

When to use it

  • A configuration loader reads `config.json` from disk with `fs.readFile` and parses it with `JSON.parse` so the app starts with the right settings.
  • An API route serializes a database result object with `JSON.stringify` before writing it to the HTTP response body.
  • A data-migration script reads a large JSON export, transforms each record, and writes the result back to disk with `JSON.stringify(data, null, 2)` for readability.

More examples

Parse and stringify JSON

Demonstrates the two core JSON methods: `JSON.parse` to deserialize and `JSON.stringify` to serialize.

Example Β· js
const raw  = '{"name":"Alice","age":30}';
const obj  = JSON.parse(raw);
console.log(obj.name); // 'Alice'

const json = JSON.stringify({ city: 'Berlin' }, null, 2);
console.log(json);
// {
//   "city": "Berlin"
// }

Read a JSON file from disk

Reads a JSON file asynchronously and parses it -- the standard way to load config files in Node.js.

Example Β· js
const { readFile } = require('fs/promises');

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

loadConfig().then(c => console.log(c.port));

Write pretty-printed JSON to file

Serializes an object with 2-space indentation using the third `JSON.stringify` argument and writes it to disk.

Example Β· js
const { writeFile } = require('fs/promises');

const report = {
  generated: new Date().toISOString(),
  records:   1042,
  errors:    3,
};

await writeFile('report.json', JSON.stringify(report, null, 2), 'utf8');
console.log('Report saved');

Discussion

  • Be the first to comment on this lesson.
Working with JSON β€” Node.js | SoundsCode