Introduction to JSON and JavaScript
\nJSON (JavaScript Object Notation) is a lightweight data interchange format that has become the standard for client-server communication in web applications. Due to its simplicity and readability, JSON is used everywhere: from configuration files to API requests. In this article, we will explore how to work with JSON in the Node.js environment, master parsing (converting a string into an object) and serialization (converting an object into a string). The material is intended for beginner developers already familiar with the basics of JavaScript.
\n\nWhat is JSON and why is it needed?
\nJSON is a text format based on the syntax of JavaScript objects. However, JSON is simply a string that can be transmitted over a network or stored in a file. The main data types in JSON are:
\n- \n
- Strings (in double quotes) \n
- Numbers (integers and floating-point) \n
- Booleans (true/false) \n
- null \n
- Arrays \n
- Objects (keys in double quotes) \n
Example of a valid JSON string:
\n{\n "name": "Anna",\n "age": 28,\n "isStudent": false,\n "skills": ["JavaScript", "Node.js"],\n "address": null\n}\nUnlike a regular JavaScript object, JSON requires strict syntax: all keys and string values must be enclosed in double quotes, and comments are not allowed.
\n\nParsing JSON: JSON.parse()
\nTo convert a JSON string into a JavaScript object, the method JSON.parse() is used. This is necessary when you receive data from a server, read a file, or process user input.
Basic parsing example
\nconst jsonString = '{"name": "Ivan", "age": 30}';\nconst user = JSON.parse(jsonString);\nconsole.log(user.name); // Ivan\nconsole.log(user.age); // 30\n\nParsing an array
\nconst jsonArray = '[1, 2, "three", true]';\nconst arr = JSON.parse(jsonArray);\nconsole.log(arr[2]); // three\n\nParsing error handling
\nInvalid JSON will throw a SyntaxError exception. Always use try...catch when working with untrusted data:
try {\n const invalid = '{"name": "Error}';\n const result = JSON.parse(invalid);\n} catch (error) {\n console.error('Parsing error:', error.message);\n}\nYou can also pass a second argument — a reviver function that allows transforming values during parsing:
const json = '{"date": "2024-01-15", "count": "42"}';\nconst obj = JSON.parse(json, (key, value) => {\n if (key === 'date') return new Date(value);\n if (key === 'count') return Number(value);\n return value;\n});\nconsole.log(obj.date.getFullYear()); // 2024\nconsole.log(typeof obj.count); // number\n\nJSON Serialization: JSON.stringify()
\nThe reverse process — converting a JavaScript object into a JSON string — is performed using JSON.stringify(). This is needed for sending data to a server, saving to a file, or logging.
Simple serialization example
\nconst user = {\n name: 'Maria',\n age: 25,\n isAdmin: true\n};\nconst json = JSON.stringify(user);\nconsole.log(json);\n// {"name":"Maria","age":25,"isAdmin":true}\n\nOutput formatting
\nThe method accepts three parameters: the value, a replacer function (or an array of fields), and the number of spaces for indentation:
\nconst data = {\n id: 1,\n title: 'Article',\n tags: ['js', 'json']\n};\n// With 2-space indentation\nconst prettyJson = JSON.stringify(data, null, 2);\nconsole.log(prettyJson);\n/* Output:\n{\n "id": 1,\n "title": "Article",\n "tags": [\n "js",\n "json"\n ]\n}\n*/\n\nField filtering
\nThe second parameter can be an array of keys to include in the result:
\nconst user = {\n name: 'Peter',\n password: 'secret12