JSON processing in Node.js: a complete guide
JSON (JavaScript Object Notation) is a lightweight data interchange format based on JavaScript object syntax. In the Node.js environment, working with JSON is a daily task: from configuration files to API requests. In this article, we will cover all aspects of JSON processing in detail, including parsing, serialization, validation, and working with large files.
Basic methods: JSON.parse() and JSON.stringify()
Two main methods for working with JSON are built directly into JavaScript. They are globally available and do not require installing additional libraries.
JSON.parse() — converting a string to an object
The JSON.parse() method takes a JSON string and returns the corresponding JavaScript object. If the string contains invalid JSON, a SyntaxError exception will be thrown.
const jsonString = '{"name": "Anna", "age": 28, "isStudent": false}';const user = JSON.parse(jsonString);console.log(user.name); // "Anna"console.log(user.age); // 28An optional second parameter can be a reviver function that allows modifying values during parsing:
const json = '{"year": "2024", "price": "1500.50"}';const data = JSON.parse(json, (key, value) => { if (key === 'price') return parseFloat(value); if (key === 'year') return parseInt(value); return value;});console.log(typeof data.price); // "number"JSON.stringify() — converting an object to a string
The JSON.stringify() method does the opposite: it converts an object or value into a JSON string. It accepts up to three arguments: the value, a replacer function or array of keys, and the number of spaces for formatting.
const user = { name: "Ivan", age: 32, skills: ["JS", "Node", "Python"]};
// Without formattingconsole.log(JSON.stringify(user));// {"name":"Ivan","age":32,"skills":["JS","Node","Python"]}
// With formatting (2 spaces)console.log(JSON.stringify(user, null, 2));/*{ "name": "Ivan", "age": 32, "skills": [ "JS", "Node", "Python" ]}*/The second argument can be an array of keys for filtering:
console.log(JSON.stringify(user, ['name', 'age']));// {"name":"Ivan","age":32}Working with JSON files in Node.js
In Node.js, it is often necessary to read and write JSON files. The fs (file system) modules are used for this.
Reading a JSON file
const fs = require('fs');
// Synchronous readingtry { const data = fs.readFileSync('config.json', 'utf8'); const config = JSON.parse(data); console.log(config.port);} catch (err) { console.error('File reading error:', err.message);}
// Asynchronous readingfs.readFile('config.json', 'utf8', (err, data) => { if (err) { console.error('Error:', err); return; } const config = JSON.parse(data); console.log(config.port);});Writing a JSON file
const fs = require('fs');
const settings = { theme: 'dark', language: 'en', fontSize: 14};
// Synchronous writingfs.writeFileSync('settings.json', JSON.stringify(settings, null, 2));
// Asynchronous writingfs.writeFile('settings.json', JSON.stringify(settings, null, 2), (err) => { if (err) console.error('Write error:', err); else console.log('File saved');});JSON validation
Before using data, it is always worth checking its validity. The simplest way is to wrap JSON.parse() in a try-catch. For more complex structure validation, libraries can be used.
Checking with try-catch
function safeJsonParse(str) { try { return { data: JSON.parse(str), error: null }; } catch (e) { return { data: null, error: e.message }; }}