JSON Processing in JavaScript (Node.js): A Complete Guide

Online Python Trainer for Beginners

Learn Python easily without overwhelming theory. Solve practical tasks with automatic checking, get hints in Russian, and write code directly in your browser — no installation required.

Start Course

Working with JSON in Node.js: From Basics to Advanced Techniques



JSON (JavaScript Object Notation) is a lightweight data interchange format that has become the de facto standard for web APIs and configuration files. In Node.js, JSON handling is built into the core, making its processing fast and convenient. In this article, we will cover all aspects of working with JSON: from basic parsing to processing large files using streams.



Basics: JSON.parse() and JSON.stringify()



Two global methods — JSON.parse() and JSON.stringify() — are the foundation of all JSON work in JavaScript.



JSON.parse() — Converting a String to an Object



The JSON.parse() method takes a JSON-formatted string and returns the corresponding JavaScript object. If the string contains a syntax error, a SyntaxError exception will be thrown.



const jsonString = '{"name": "Anna", "age": 30, "isAdmin": false}';const user = JSON.parse(jsonString);

console.log(user.name); // "Anna"console.log(user.age); // 30


The second optional parameter is a reviver function, which allows you to transform values during parsing:



const jsonString = '{"date": "2024-01-15T10:30:00Z", "count": "42"}';const obj = JSON.parse(jsonString, (key, value) => {    if (key === 'date') return new Date(value);    if (key === 'count') return parseInt(value, 10);    return value;});

console.log(obj.date instanceof Date); // trueconsole.log(typeof obj.count); // "number"


JSON.stringify() — Converting an Object to a String



The JSON.stringify() method does the opposite — it turns a JavaScript object into a JSON string. It takes three parameters: the value, a replacer function (or an array of keys), and the number of spaces for formatting.



const user = {    name: "Ivan",    age: 25,    roles: ["admin", "editor"],    metadata: null};

// Basic usageconst json = JSON.stringify(user);console.log(json);// {"name":"Ivan","age":25,"roles":["admin","editor"],"metadata":null}

// With formattingconst prettyJson = JSON.stringify(user, null, 2);console.log(prettyJson);/*{ "name": "Ivan", "age": 25, "roles": ["admin", "editor"], "metadata": null}*/


The replacer function allows you to filter or transform values:



const user = { name: "Petr", password: "secret123", age: 28 };

const safeJson = JSON.stringify(user, (key, value) => { if (key === 'password') return undefined; // remove password return value;});

console.log(safeJson); // {"name":"Petr","age":28}


Reading and Writing JSON Files in Node.js



In real projects, JSON data is often stored in files. Node.js provides the fs (file system) module for working with the file system.



Reading JSON from a File



const fs = require('fs');

// Synchronous readingtry { const data = fs.readFileSync('config.json', 'utf8'); const config = JSON.parse(data); console.log(config.port); // 3000} catch (err) { console.error('Error reading file:', err.message);}

// Asynchronous reading (recommended)fs.readFile('config.json', 'utf8', (err, data) => { if (err) { console.error('Error:', err); return; } const config = JSON.parse(data); console.log(config);});


Writing JSON to a File



const fs = require('fs');

const settings = { theme: "dark", language: "en", notifications: true};

// Writing with formattingfs.writeFileSync('settings.json', JSON.stringify(settings, null, 2), 'utf8');console.log('File settings.json created');

// Asynchronous writingfs.writeFile('settings.json', JSON.stringify(settings), (err) => { if (err) throw err;

Recommendations