There are two powerful methods in JavaScript for handling JSON data: JSON.parse() and JSON.stringify(). These methods are commonly used to convert between JSON strings and JavaScript objects.

JSON.stringify() is used to convert a JavaScript object into a JSON string. This is useful when you want to store or transmit data in a format that can be easily shared or transferred between systems.

Here’s how you can use the JSON.stringify() method:

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

In the example, the JavaScript object user is converted into a JSON string that looks like this:

'{"name":"John","age":30,"isAdmin":true}'

The JSON.stringify() method also accepts an optional parameter called a replacer, which can be a function or an array. Here is an example of using an array for the optional replacer parameter:

const developerObj = {
  firstName: "Jessica",
  isAwesome: true,
  isMusician: true,
  country: "USA",
};
 
// result: {"firstName":"Jessica","country":"USA"}
console.log(JSON.stringify(developerObj, ["firstName", "country"]));

In this example, we have a developerObj with four properties. When we use the JSON.stringify() method, we can pass in an array for the second parameter and specify which properties we want stringified. The result will be a stringified object containing only the firstName and country properties.

Another optional parameter for the JSON.stringify() method would be the spacer parameter. This allows you to control the spacing for the stringified result:

const developerObj = {
  firstName: "Jessica",
  isAwesome: true,
  isMusician: true,
  country: "USA",
};
 
console.log(JSON.stringify(developerObj, null, 2));
 
/* result
{
  "firstName": "Jessica",
  "isAwesome": true,
  "isMusician": true,
  "country": "USA"
}
*/

Most of the time you will not be using either of these optional parameters for the JSON.stringify() method but it is still helpful to be aware of them.

Another method you will be using a lot in your programming is the JSON.parse() method. JSON.parse() converts a JSON string back into a JavaScript object. This is useful when you retrieve JSON data from a web server or from localStorage and you need to manipulate the data in your application. You will learn more about localStorage in a future lecture.

Here’s an example on how to work with the JSON.parse() method:

const jsonString = '{"name":"John","age":30,"isAdmin":true}';
const userObject = JSON.parse(jsonString);

The JSON string is parsed back into a JavaScript object that looks like this:

{
  name: "John",
  age: 30,
  isAdmin: true
}

This allows you to work with the data in your program as a normal JavaScript object, making it easier to manipulate and use.

In future modules, we will continue to learn more about how to work with JSON and the JSON.parse() and JSON.stringify() methods.