JS JSON
In this page:
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?
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()
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()
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
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
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
Chapter Quiz — Complete all 26 topics to unlock
0/26 topics done
Complete these topics first:
- JS JSON
- JS Regular Expressions
- JS Fetch API
- JS LocalStorage and SessionStorage
- JS Cookies
- JS setTimeout and setInterval
- JS Event Loop
- JS Web Workers
- JS Service Workers
- JS AJAX
- JS AJAX Intro
- JS AJAX XMLHttp
- JS AJAX Request
- JS AJAX Response
- JS AJAX XML
- JS AJAX PHP
- JS AJAX Database
- JS JSONP
- JS RegExp Flags
- JS RegExp Classes
- JS RegExp Metachars
- JS RegExp Assertions
- JS RegExp Groups
- JS RegExp Quantifiers
- JS JSON HTML
- JS JSON vs XML