Introduction: What is JSON and why is it needed in JavaScript?
JSON (JavaScript Object Notation) is a lightweight text-based data interchange format based on JavaScript object syntax. Despite its name, JSON is language-independent and is supported by virtually all modern programming languages. In the Node.js ecosystem and browser JavaScript, working with JSON is one of the most common operations: from fetching data from APIs to saving configurations and transferring information between the server and client.
In this article, we will cover two key methods: JSON.parse() (converting a JSON string into a JavaScript object) and JSON.stringify() (converting a JavaScript object into a JSON string). You will learn how to properly handle errors, work with nested structures, and use advanced features of these methods.
1. Parsing JSON: The JSON.parse() Method
The JSON.parse() method takes a JSON-formatted string and converts it into a JavaScript object, array, or primitive value. This is the primary operation when you receive data from an external source — for example, from a REST API or a file.
Basic Syntax
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); // falseNote: keys and string values in JSON must be enclosed in double quotes. Single quotes or unquoted keys will cause an error.
Parsing Arrays
JSON can contain not only objects but also arrays:
const jsonArray = '[1, 2, 3, "four", true]';const arr = JSON.parse(jsonArray);
console.log(arr[0]); // 1console.log(arr[3]); // "four"Nested Structures
JSON supports unlimited nesting:
const complexJson = '{"users":[{"id":1,"name":"Ivan"},{"id":2,"name":"Maria"}]}';const data = JSON.parse(complexJson);
console.log(data.users[0].name); // "Ivan"console.log(data.users[1].id); // 2Parsing Error Handling
If the string contains invalid JSON, JSON.parse() will throw a SyntaxError. Always use try/catch when working with external data:
const invalidJson = '{"name": "Peter", age: 25}'; // Error: age without quotes
try { const obj = JSON.parse(invalidJson); console.log(obj);} catch (error) { console.error('JSON parsing error:', error.message); // Output: JSON parsing error: Unexpected token 'a', ...}Advanced Usage: The Reviver Function
The second parameter of JSON.parse() is a reviver function, which allows you to transform values during parsing. For example, you can automatically convert date strings into Date objects:
const jsonWithDate = '{"name": "Event", "date": "2025-03-15T10:00:00.000Z"}';
const event = JSON.parse(jsonWithDate, (key, value) => { if (key === 'date') { return new Date(value); } return value;});
console.log(event.date instanceof Date); // trueconsole.log(event.date.getFullYear()); // 20252. JSON Serialization: The JSON.stringify() Method
The JSON.stringify() method performs the reverse operation — it converts a JavaScript object or value into a JSON string. This is necessary for sending data to a server, saving to a file, or logging.
Basic Syntax
const user = { name: "Olga", age: 28, isAdmin: true, skills: ["JS", "Python", "SQL"]};
const jsonString = JSON.stringify(user);console.log(jsonString);// {"name":"Olga