Working with JSON in JavaScript: Parsing and Serialization in Practice
JSON (JavaScript Object Notation) is a lightweight data interchange format widely used in modern web applications. In JavaScript, working with JSON is built into the language, making it an ideal tool for data exchange between client and server, as well as for storing configurations. In this article, we will break down how to parse and serialize JSON in the Node.js environment, explore practical examples, and discuss best practices.
What is JSON and Why is it Needed?
JSON is a text format based on JavaScript object syntax. It supports the following data types:
- Strings (in double quotes)
- Numbers (integers and floating-point)
- Boolean values (true/false)
- Arrays
- Objects
- null
JSON is used everywhere: from API requests to configuration files (e.g., package.json). In Node.js, JSON is the primary format for data exchange between microservices.
Parsing JSON: Converting a String into an Object
To convert a JSON string into a JavaScript object, the JSON.parse() method is used. Let's look at a basic example:
const jsonString = '{"name": "Anna", "age": 30, "isStudent": false}';const user = JSON.parse(jsonString);
console.log(user.name); // "Anna"console.log(user.age); // 30console.log(user.isStudent); // falseImportant: The JSON string must be strictly formatted. All keys and string values must be in double quotes. Single quotes or trailing commas will cause an error.
Error Handling During Parsing
When working with external data (from files, APIs), there is always a risk of receiving invalid JSON. Use try...catch:
const fs = require('fs');
try { const data = fs.readFileSync('data.json', 'utf8'); const parsed = JSON.parse(data); console.log('Successfully parsed:', parsed);} catch (error) { if (error instanceof SyntaxError) { console.error('JSON syntax error:', error.message); } else { console.error('File reading error:', error.message); }}Parsing with a Reviver Function
The JSON.parse() method accepts a second argument — a function that can transform values. This is useful, for example, for converting date strings into Date objects:
const json = '{"name": "Ivan", "birthDate": "1990-05-15T00:00:00Z"}';const user = JSON.parse(json, (key, value) => { if (key === 'birthDate') { return new Date(value); } return value;});
console.log(user.birthDate instanceof Date); // trueconsole.log(user.birthDate.getFullYear()); // 1990JSON Serialization: Converting an Object into a String
The reverse process — converting a JavaScript object into a JSON string — is performed using JSON.stringify().
const user = { name: 'Maria', age: 25, skills: ['JavaScript', 'Node.js', 'Python'], isActive: true};
const jsonString = JSON.stringify(user);console.log(jsonString);// {"name":"Maria","age":25,"skills":["JavaScript","Node.js","Python"],"isActive":true}Formatting Output
For readability, you can add indentation:
const prettyJson = JSON.stringify(user, null, 2);console.log(prettyJson);/*{ "name": "Maria", "age": 25, "skills": [ "JavaScript", "Node.js", "Python" ], "isActive": true}*/Filtering and Replacing Values
The second argument of JSON.stringify() can be an array of keys (for filtering) or a replacer function:
Blogs
Book Recommendations
Read also
Working with JSON in Java: Parsing and Data Serialization
How to Write a REST API in Kotlin in 30 Minutes
How to Fix "Headers already sent" in PHP: A Complete Guide
TypeScript in 2025: New Features for Beginner Developers
Containerization of PHP Applications with Docker: A Complete Developer's Guide