Storage
Persisting configuration or application state in a text-based format.
JS Puzzles · Const
JSON.stringify converts JavaScript values to JSON text, and JSON.parse converts JSON text back into JavaScript values. JSON supports fewer types than JavaScript, so serialization can omit unsupported data.
JSON is a data-only format with a smaller type set than JavaScript. JSON.stringify converts supported values to text, while JSON.parse converts valid JSON text back to JavaScript values; unsupported properties may disappear during serialization.
let json = JSON.stringify(value[, replacer, space]);
let value = JSON.parse(str[, reviver]);| Name | Type | Description |
|---|---|---|
value | any | The JavaScript value to convert to JSON text. |
replacer | Array | function | Optional array of properties to include or function that transforms values during serialization. |
space | string | number | Optional formatting control for the serialized output. |
str | string | The JSON text to parse. |
reviver | function | Optional function that transforms parsed values. |
JSON.stringify returns a JSON string; JSON.parse returns the JavaScript value represented by the JSON text.
const input = '{"name":"Ada","count":null}';
const value = JSON.parse(input);
const output = JSON.stringify({ name: value.name, count: value.count });
console.log(output);Parses valid JSON text into a JavaScript value, then serializes selected data back to JSON.
Persisting configuration or application state in a text-based format.
Sending structured data between programs or across a network boundary.
Selecting or transforming fields before producing JSON output.
JSON.stringify converts a JavaScript value into JSON text, and JSON.parse converts JSON text into a JavaScript value. JSON supports plain objects, arrays, strings, numbers, booleans, and null.
Follow-up: What happens to a function property during stringification? It is omitted because functions are not part of JSON's data types.
JSON requires double quotes for strings and object property names. It also has a more limited type system than JavaScript, so some JavaScript-specific values cannot be represented directly.
Follow-up: Why might an object lose information after a stringify/parse round trip? Unsupported values such as functions, Symbols, and undefined properties can be skipped.
The optional replacer can be an array of properties to include or a function that transforms values during serialization. The optional reviver passed to JSON.parse can transform parsed values while reading them.
Follow-up: When would a reviver be useful? It can convert specially formatted JSON values, such as date strings, into richer JavaScript values during parsing.
JSON.stringifyJSON.parsereplacerrevivertoJSON