Working with JSON in JavaScript: Parsing and Serialization for Beginners

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

Introduction to JSON and JavaScript

\n

JSON (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\n

What is JSON and why is it needed?

\n

JSON 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
\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}
\n

Unlike 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\n

Parsing JSON: JSON.parse()

\n

To 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.

\n\n

Basic parsing example

\n
const jsonString = '{"name": "Ivan", "age": 30}';\nconst user = JSON.parse(jsonString);\nconsole.log(user.name); // Ivan\nconsole.log(user.age);  // 30
\n\n

Parsing an array

\n
const jsonArray = '[1, 2, "three", true]';\nconst arr = JSON.parse(jsonArray);\nconsole.log(arr[2]); // three
\n\n

Parsing error handling

\n

Invalid JSON will throw a SyntaxError exception. Always use try...catch when working with untrusted data:

\n
try {\n  const invalid = '{"name": "Error}';\n  const result = JSON.parse(invalid);\n} catch (error) {\n  console.error('Parsing error:', error.message);\n}
\n

You can also pass a second argument — a reviver function that allows transforming values during parsing:

\n
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\n

JSON Serialization: JSON.stringify()

\n

The 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.

\n\n

Simple serialization example

\n
const 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\n

Output formatting

\n

The method accepts three parameters: the value, a replacer function (or an array of fields), and the number of spaces for indentation:

\n
const 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\n

Field filtering

\n

The second parameter can be an array of keys to include in the result:

\n
const user = {\n  name: 'Peter',\n  password: 'secret12                

Blogs

Book Recommendations