JS JSON
JSON (JavaScript Object Notation) is a text format for exchanging data — a subset of JavaScript's object literal syntax. Every modern API speaks it.
Allowed value types
| Allowed | Example | NOT allowed |
|---|---|---|
| String | "hello" (double quotes only) | Single quotes, no quotes on keys |
| Number | 42, 3.14 | NaN, Infinity |
| Boolean | true, false | — |
| Null | null | undefined |
| Array | [1, 2, 3] | Trailing commas |
| Object | { "name": "Ada" } | Functions, dates, regex, comments |
Parse and stringify
JS
// Object → JSON string
const json = JSON.stringify({ name: "Ada", age: 36 });
// '{"name":"Ada","age":36}'
// Pretty-print with 2-space indent
JSON.stringify(obj, null, 2);
// JSON string → object
const obj = JSON.parse(json);
// Safer: handle parse errors
try { return JSON.parse(input); }
catch (e) { return null; }
Talking to an API
JS
// GET
const user = await fetch("/api/user").then(r => r.json());
// POST
const res = await fetch("/api/user", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ name: "Ada" }),
});
const created = await res.json();
Replacers and revivers
JS
// Drop sensitive fields when serializing
JSON.stringify(user, (key, value) =>
key === "password" ? undefined : value
);
// Convert ISO dates back to Date objects when parsing
JSON.parse(json, (key, value) =>
typeof value === "string" && /^\d{4}-\d{2}-\d{2}T/.test(value)
? new Date(value)
: value
);
Note: JSON has no
undefined and no Date. Stringify drops undefined properties and converts Dates to ISO strings.Example
Example
<!DOCTYPE html>
<html>
<body>
<p id="out"></p>
<script>
document.getElementById("out").textContent = "Hello from JS JSON!";
</script>
</body>
</html>
Try it Yourself »
Exercise
Turn a JS object into a JSON string.
const text = JSON.
(user);
Opposite of parse().
Discussion
Loading…