JSON Processing in JavaScript (Node.js): 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

JSON in Node.js: Complete Guide to Data Processing



JSON (JavaScript Object Notation) is a lightweight data interchange format that has become the de facto standard for web APIs, configuration files, and storing structured information. In the Node.js environment, working with JSON is an integral part of almost any application. In this article, we will cover all aspects of JSON processing in detail: from basic parsing to advanced stream processing.



1. Basics: Parsing and Serialization



In Node.js, two global methods are used for working with JSON: JSON.parse() and JSON.stringify(). They are available without importing additional modules.



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

The JSON.parse() method takes a JSON string and returns the corresponding JavaScript object. It is important that the string must be strictly valid JSON.



const jsonString = '{"name": "Alice", "age": 30, "isAdmin": false}';const user = JSON.parse(jsonString);console.log(user.name); // Aliceconsole.log(typeof user); // object


The method also supports a second argument — a "reviver" function that allows transforming values during parsing:



const data = '{"date": "2025-01-15T10:00:00Z"}';const parsed = JSON.parse(data, (key, value) => {    if (key === 'date') return new Date(value);    return value;});console.log(parsed.date instanceof Date); // true


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

The JSON.stringify() method does the reverse conversion — it turns a JavaScript object into a JSON string.



const user = {    name: 'Bob',    age: 25,    hobbies: ['coding', 'reading']};const json = JSON.stringify(user);console.log(json); // {"name":"Bob","age":25,"hobbies":["coding","reading"]}


The method accepts three arguments: the value, a replacer function, and the number of spaces for formatting (space):



const obj = { a: 1, b: 2, c: 3 };// Formatted output with indentationconsole.log(JSON.stringify(obj, null, 2));// {//   "a": 1,//   "b": 2,//   "c": 3// }

// Filtering keys using replacerconst filtered = JSON.stringify(obj, ['a', 'c'], 2);console.log(filtered);// {// "a": 1,// "c": 3// }


2. Reading and Writing JSON Files



In real applications, JSON data is often stored in files. The built-in fs module is used for working with the file system.



Synchronous Reading and Writing

const fs = require('fs');const path = require('path');

const filePath = path.join(__dirname, 'config.json');

// Readingconst rawData = fs.readFileSync(filePath, 'utf-8');const config = JSON.parse(rawData);console.log(config.port);

// Writingconst newConfig = { port: 3000, host: 'localhost' };fs.writeFileSync(filePath, JSON.stringify(newConfig, null, 2));


Asynchronous Reading and Writing (Recommended Approach)

const fs = require('fs').promises;

async function readConfig() { try { const data = await fs.readFile('config.json', 'utf-8'); return JSON.parse(data); } catch (err) { console.error('Error reading file:', err); throw err; }}

async function writeConfig(config) { await fs.writeFile('config.json', JSON.stringify(config, null, 2));}

// Usage(async () => { const config = await readConfig(); config.port = 4000; await writeConfig(config);})();


3. JSON Validation



Sometimes it is necessary to check whether a string is valid JSON without throwing an exception. The most reliable way is to wrap JSON.parse() in a try-catch:




                
    
    

Recommendations