๐ŸŽ“ A1Learner
๐Ÿ”

JavaScript JSON

JSON is a text format for storing and sending data in a fixed shape. Programs exchange data as JSON text, then turn the text back into values they can use.

Parse text into an object

JSON.parse reads the text and builds a real object. The typeof check proves the result is an object.

const text = '{"name":"Mia","age":30}';
const person = JSON.parse(text);
console.log(person.name, typeof person);

Turn an object into text

JSON.stringify writes the object as text. The keys appear in the same order as the object literal.

const person = { name: "Mia", age: 30 };
const text = JSON.stringify(person);
console.log(text);

Parse an array

JSON text can hold an array at the top level. Parsing it gives a real array with a length.

const colors = JSON.parse('["red","blue","green"]');
console.log(colors.length);

Example

const user = { name: "Leo", age: 25, admin: false };
const text = JSON.stringify(user);
console.log(text);
const back = JSON.parse(text);
console.log(back.name, back.age);

Key points

  • JSON stands for JavaScript Object Notation.
  • JSON.parse turns JSON text into a JavaScript value.
  • JSON.stringify turns a JavaScript value into JSON text.
  • Property names in JSON text need double quotes.
  • JSON can hold text, numbers, booleans, arrays, objects and null.
  • JSON cannot hold functions.

In this example, stringify turns the user object into JSON text for sending or storing. parse then turns that same text back into an object. The name and age read from the new object match the original values.

Try it Yourself

Edit the code, then press Run.

Runs in your browser โ€” the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.

Exercise

What does JSON.parse do?