JSON vs JavaScript Objects: Parse and Stringify Explained

Understand JSON as a text format, compare it with JavaScript objects, and learn how JSON.parse() and JSON.stringify() work with APIs and storage.

JSON vs JavaScript Objects: Parse and Stringify Explained

What is JSON, and How is it different from a JavaScript Object?

JSON (JavaScript Object Notation) is a text format for representing and exchanging structured data. APIs commonly send and receive JSON. A JavaScript object, by contrast, is a value your program can work with in memory.

The same data can be written in a similar-looking way, but the two are not the same thing:

// A JavaScript object value
const user = {
  name: "Likhon",
  active: true,
};

// A JSON string containing similar data
const userJson = '{"name":"Likhon","active":true}';

user is an object. userJson is a string. JSON is text that follows a defined syntax; it is not an object that your JavaScript code can access with userJson.name.

Convert an object to JSON with JSON.stringify()

Use JSON.stringify() to serialize a JavaScript value into JSON text:

const product = {
  name: "Keyboard",
  price: 80,
};

const productJson = JSON.stringify(product);

console.log(productJson); // '{"name":"Keyboard","price":80}'
console.log(typeof productJson); // "string"

This is useful when sending a request body or storing an object in Web Storage, because those interfaces work with text values. For example:

localStorage.setItem("product", JSON.stringify(product));

Convert JSON text to a JavaScript value with JSON.parse()

Use JSON.parse() to read JSON text and get a JavaScript value back:

const savedText = localStorage.getItem("product");
const savedProduct = JSON.parse(savedText);

console.log(savedProduct.name); // "Keyboard"
console.log(typeof savedProduct); // "object"

If the text is not valid JSON, JSON.parse() throws a SyntaxError. When data may be missing or malformed, handle that possibility:

const savedText = localStorage.getItem("product");
let savedProduct = null;

if (savedText !== null) {
  try {
    savedProduct = JSON.parse(savedText);
  } catch (error) {
    console.error("Stored product data is not valid JSON", error);
  }
}

JSON has stricter rules than JavaScript object literals

JSON resembles an object literal, but it has stricter syntax. Object keys and strings must use double quotes. JSON does not support comments, functions, undefined, or trailing commas.

// Valid JSON text
const validJson = '{"name":"Mina","score":90}';

// Not valid JSON: single quotes and an unquoted key
// const invalidJson = "{'name': 'Mina'}";

JSON values can be objects, arrays, strings, numbers, booleans, or null. JSON is a data format; it cannot represent every JavaScript value. For example, JSON.stringify() omits object properties whose values are functions or undefined, and converts such values in arrays to null. Avoid relying on serialization for values outside JSON's data types.

JSON with Fetch

When an API returns JSON, response.json() reads the response body and parses it into a JavaScript value. You do not need to call JSON.parse() again:

const response = await fetch("/api/products");

if (!response.ok) {
  throw new Error(`Request failed: ${response.status}`);
}

const products = await response.json(); // JavaScript value
console.log(products[0].name);

When sending JSON, convert your object to text with JSON.stringify() and tell the server the format using the content type header:

const response = await fetch("/api/products", {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
  },
  body: JSON.stringify({ name: "Keyboard", price: 80 }),
});

A useful way to remember

  • JavaScript object: a value your program can read and update in memory.
  • JSON: text used to represent and exchange data.
  • JSON.stringify(value): JavaScript value → JSON text.
  • JSON.parse(text): JSON text → JavaScript value.

Try it yourself

Create an object for a book with a title, author, and page count. Convert it to JSON text, print its type, then parse it back and print the title. What happens if you try parsing the text "{title: 'Book'}"?

Recap

  • JSON is a text-based data format; a JavaScript object is an in-memory value.
  • Use JSON.stringify() to serialize supported values to JSON text.
  • Use JSON.parse() to turn valid JSON text into a JavaScript value.
  • JSON syntax is stricter than JavaScript object literal syntax.
  • Fetch's response.json() parses a JSON response body for you.

What's next?

Next, we’ll learn what AbortController is and when to use it to cancel an asynchronous operation such as a Fetch request.

Written by

Dev Likhon

Dev Likhon

Full Stack Developer & Tech Educator

6+ years of professional development experience.

About Me
Share:

Comments

Share what you learned or ask a question.

Loading comments...