Code Self Study Forum

[Tutorial] What is the difference between JSON and JavaScript Objects

Here’s a quick explanation of some differences between JavaScript objects and JSON.

JavaScript Objects

A JavaScript object is a collection of key-value pairs that looks like this:

const hobbit = {
    name: "Frodo",
    age: 33,
    equipment: ["mithril shirt", "ring", "short sword"],
};

To access values, you can use dot-syntax:

console.log(hobbit.name); // "Frodo"
console.log(hobbit.age);  // 33

If you check the type of the hobbit, it’s an object:

console.log(typeof hobbit); // object

If you log the type of the object’s values, they are various types:

console.log(typeof hobbit.name); // string
console.log(typeof hobbit.age);  // number
console.log(Array.isArray(hobbit.equipment)); // true

JSON

JSON stands for “JavaScript Object Notation”. It’s a string representation of a JavaScript object. It always has the type string.

You can turn a JavaScript object into a string with JSON.stringify:

const jsonHobbit = JSON.stringify(hobbit);
console.log(jsonHobbit);
//=> '{"name":"Frodo","age":33,"equipment":["mithril shirt","ring","short sword"]}'

Because it’s a string, it doesn’t have fields, and you can’t do things like:

// this will be `undefined`, because a string doesn't have a `name` attribute
console.log(jsonHobbit.name);

Why use one or the other?

JavaScript objects are how you use data in your code. JSON is a convenient way to transfer data across the network. The network doesn’t need to know about the contents of the string, it just has to get the string from one end of the network to the other.

Each side can read and write the JSON into formats that it understands. In JavaScript, you can read a string of JSON into a JavaScript object with JSON.parse and turn it back into JSON with JSON.stringify.

Here are more examples of the differences:

// this is JSON (a string with a specific kind of format)
const someJson = '{"message":"a"}';

// this is a JS object, with object-specific methods
const someObj = { message: "b" };

console.log("someJson:", someJson);
console.log("someJson type:", typeof someJson); // string
console.log("=======");

console.log("someObj:", someObj);
console.log("someObj type:", typeof someObj); // object
console.log("=======");

// turn a JSON (string) into a JS object with `JSON.parse`
const jsonConvertedToObject = JSON.parse(someJson);
console.log("now jsonConvertedToObject is:", jsonConvertedToObject);
console.log("jsonConvertedToObject type:", typeof jsonConvertedToObject); // object
console.log("=======");

// convert a JS object to a string (JSON) with `JSON.stringify`
const objectConvertedToJsonString = JSON.stringify(someObj);
console.log("now objectConvertedToJsonString is", objectConvertedToJsonString);
console.log("objectConvertedToJsonString type:", typeof objectConvertedToJsonString); // string
2 Likes