Two functions that move data in and out of text.
Direct answer
JSON.parse(text) turns a JSON string into a JavaScript object. JSON.stringify(value) turns a value into a JSON string. Wrap JSON.parse in try/catch, because invalid JSON throws an error.
Examples
const obj = JSON.parse('{"name":"Ada","age":28}');
const text = JSON.stringify({ name: "Ada", skills: ["math", "code"] }, null, 2);
The null, 2 makes the output indented and easier to read.
Safe parsing
function safeParse(text, fallback = null) {
try {
return JSON.parse(text);
} catch {
return fallback;
}
}
What does not survive
| Value | Result |
|---|---|
undefined and functions | dropped |
Date | becomes a string |
NaN and Infinity | become null |
| Circular references | throw an error |
Where Teyro fits
Teyro's Interactive Web Pages with JavaScript course turns this into short lessons you can play in a few minutes a day. It has 37 lessons, and you can start free.
The bottom line
Great for storage and APIs. Know what it drops.


