Deno logoDenoby example

Beginner

clideployweb

Parsing and serializing JSON

JSON is a widely used data interchange format. It is a human-readable, but also easially machine-readable.

To parse a JSON string, you can use the builtin JSON.parse function. The value is returned as a JavaScript object.
const text = `{
  "hello": "world",
  "numbers": [1, 2, 3]
}`;
const data = JSON.parse(text);
console.log(data.hello);
console.log(data.numbers.length);
To turn a JavaScript object into a JSON string, you can use the builtin JSON.stringify function.
const obj = {
  hello: "world",
  numbers: [1, 2, 3],
};
const json = JSON.stringify(obj);
console.log(json);
// {"hello":"world","numbers":[1,2,3]}
By default JSON.stringify will output a minified JSON string. You can customize this by specifying an indentation number in the third argument.
const json2 = JSON.stringify(obj, null, 2);
console.log(json2);
// {
//   "hello": "world",
//   "numbers": [
//     1,
//     2,
//     3
//   ]
// }

Run this example locally using the Deno CLI:

deno run https://byexample-wwv03xf36j0g.deno.dev/parsing-serializing-json.ts

Additional resources: