Working with JSON
Converting between JavaScript objects and JSON strings with JSON.stringify and JSON.parse.
2 min read
JSON (JavaScript Object Notation) is a text-based data format for representing structured data — objects, arrays, strings, numbers, booleans, and null. It's the near-universal format APIs use to send and receive data, and despite the name, it's used by virtually every programming language, not just JavaScript.
JSON is text, not a JavaScript object
This is the core thing to keep straight: a JSON string looks a lot like a JavaScript object literal, but it's just a string until you parse it.
const jsonString = '{"name": "Ada", "age": 36, "active": true}';
typeof jsonString; // "string" -- not an object yetParsing JSON into a JavaScript object
const jsonString = '{"name": "Ada", "age": 36}';
const user = JSON.parse(jsonString);
console.log(user.name); // "Ada"
typeof user; // "object"JSON.parse throws a SyntaxError if the string isn't valid JSON — trailing commas, single quotes instead of double quotes, and unquoted keys are all valid in a JavaScript object literal but invalid in JSON, and will cause JSON.parse to fail. Wrapping it in try/catch, as covered in the previous lesson, is standard practice whenever the JSON comes from an external source like an API response.
Converting a JavaScript object into JSON
const user = { name: "Ada", age: 36, active: true };
const jsonString = JSON.stringify(user);
console.log(jsonString); // '{"name":"Ada","age":36,"active":true}'This is exactly what happens under the hood in fetch() requests that send a JSON body, covered earlier: body: JSON.stringify(payload).
Pretty-printing for readability
JSON.stringify accepts extra arguments for formatting — useful when logging or displaying JSON to a human:
JSON.stringify(user, null, 2);
// {
// "name": "Ada",
// "age": 36,
// "active": true
// }The second argument (a replacer, here null) can filter or transform values; the third sets the indentation.
What JSON can't represent
JSON only supports a limited set of value types. undefined, functions, and Symbol values are silently dropped when stringifying an object; Date objects get converted to ISO date strings (and don't automatically convert back to Date objects when parsed):
JSON.stringify({ name: "Ada", greet: function () {}, id: undefined });
// '{"name":"Ada"}' -- greet and id are both goneThis is worth remembering when an API response looks like it's missing a field you expected — check whether the original data actually had a type JSON can represent.
That covers the full arc of this course: from a single console.log line through variables, functions, the DOM, asynchronous code, and now the data format that ties a JavaScript program to the outside world. From here, the TypeScript course builds directly on this foundation, adding a static type system on top of the same language.