2 min read

JSON Methods

JSON (JavaScript Object Notation) is a standard text-based format for representing structured data based on JavaScript object syntax. JavaScript provides a global JSON object with methods to convert between JSON strings and JavaScript objects.

1. JSON.parse()

The JSON.parse() method parses a JSON string, constructing the JavaScript value or object described by the string.

const jsonString = '{"name": "Alice", "age": 25, "isAdmin": false}';
const user = JSON.parse(jsonString);

console.log(user.name); // "Alice"
console.log(user.age);  // 25

The Reviver Parameter

JSON.parse() accepts an optional second argument, a reviver function, which can transform the result before it is returned.

const jsonString = '{"name": "Alice", "birthDate": "2023-01-01T00:00:00.000Z"}';

const user = JSON.parse(jsonString, (key, value) => {
  if (key === 'birthDate') {
    return new Date(value);
  }
  return value;
});

console.log(user.birthDate.getFullYear()); // 2023

2. JSON.stringify()

The JSON.stringify() method converts a JavaScript object or value to a JSON string.

const user = {
  name: "Bob",
  age: 30,
  isAdmin: true
};

const jsonString = JSON.stringify(user);
console.log(jsonString);
// '{"name":"Bob","age":30,"isAdmin":true}'

The Replacer Parameter

The second argument is a replacer, which can be an array of keys to keep, or a function to alter the stringification process.

const user = { name: "Bob", age: 30, password: "secret_password" };

// Only keep 'name' and 'age'
console.log(JSON.stringify(user, ["name", "age"]));
// '{"name":"Bob","age":30}'

The Space Parameter

The third argument is space, used to insert white space into the output JSON string for readability (pretty-printing).

console.log(JSON.stringify(user, null, 2));

programming/javascript/vanilla/javascript programming/javascript/vanilla/data-types