← Back to JavaScript Course | Chapter 9: Async & Web APIs | Lesson 1 of 26

JS JSON

What Is JSON?

JSON is a text format used to store and exchange data. Its simple, language-independent syntax made JSON the standard format for web APIs, configuration files, and data sent between a server and a browser.

Example: What Is JSON?

javascript
const data = { name: "Sam", age: 30 };
const jsonString = JSON.stringify(data);
console.log(jsonString); // used to exchange data with APIs

JSON.parse()

JSON.parse() converts a JSON string into a JavaScript value. If the string isn't valid JSON, JSON.parse() throws a SyntaxError, so parsing untrusted input should generally be wrapped in a try/catch.

Example: JSON.parse()

javascript
const jsonString = '{"name": "Sam", "age": 30}';
const obj = JSON.parse(jsonString);
console.log(obj.name);

JSON.stringify()

JSON.stringify() converts a JavaScript value into a JSON string. Functions, undefined values, and symbols are silently dropped by JSON.stringify(), since JSON has no way to represent them — worth knowing before you rely on a round-trip being lossless.

Example: JSON.stringify()

javascript
const data = { name: "Sam", greet: function () {}, id: undefined };
console.log(JSON.stringify(data)); // functions/undefined dropped

JSON Data Types

JSON supports strings, numbers, booleans, null, objects, and arrays. Because JSON has no concept of dates or functions, those need to be converted to plain values (like an ISO date string) before stringifying, and converted back manually after parsing.

Example: JSON Data Types

javascript
console.log(JSON.stringify({ a: 1, b: "text", c: true, d: null, e: [1, 2] }));

Practical JSON

JSON is commonly used with APIs, configuration files, and saved application data. A typical fetch() call parses a JSON response body with response.json(), and a typical POST request stringifies a JavaScript object before sending it in the request body.

Example: Practical JSON

javascript
const payload = JSON.stringify({ name: "Sam" });
console.log(payload); // typical POST body
const response = JSON.parse(payload);
console.log(response.name); // typical parsed API response

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.