🧅JSON.parse(string) / JSON.stringify(object)

JSON.parse is a method that parses a JSON string and constructs the JavaScript value or object described by the string. It takes a single argument, which is the JSON string to be parsed. For example:

const jsonString = '{"name":"John","age":30,"city":"New York"}';
const obj = JSON.parse(jsonString);

console.log(obj.name); // "John"

In this example, the jsonString variable contains a JSON string representing an object with properties for a person's name, age, and city. We use JSON.parse to parse the string and create a JavaScript object from it. We can then access the object's properties using dot notation (.name, .age, .city).

JSON.stringify is a method that takes a JavaScript value and produces a JSON string representation of it. It takes a single argument, which is the value to be converted to a JSON string. For example:

const obj = {
  name: 'John',
  age: 30,
  city: 'New York'
};
const jsonString = JSON.stringify(obj);

console.log(jsonString); // '{"name":"John","age":30,"city":"New York"}'

In this example, the obj variable contains a JavaScript object with properties for a person's name, age, and city. We use JSON.stringify to convert the object to a JSON string. The resulting string can then be saved to a file, sent over the internet as part of an HTTP request, or used for any other purpose that requires a JSON string.

Last updated