JSON.parse()
and JSON.stringify()
are two important functions in JavaScript for working with JSON data.
JSON.parse()
is used to parse a JSON string and convert it into a JavaScript object.
JSON.parse(text[, reviver])
-
text
: The JSON string to parse. -
reviver (optional)
: A function that will be called for each key-value pair in the resulting object, with the key and value as arguments. The return value of this function will be used as the value for that key. (Optional)
const jsonString = '{"name": "John", "age": 30}';
const person = JSON.parse(jsonString);
console.log(person.name); // Output: John
console.log(person.age); // Output: 30
JSON.stringify()
JSON.stringify()
is used to convert a JavaScript object into a JSON string.
JSON.stringify(value[, replacer[, space]])
-
value
: The JavaScript value to convert to a JSON string. -
replacer (optional)
: A function that transforms the results. It can be an array of strings or numbers that will act as a whitelist for selecting the properties you want to include in the resulting JSON string. (Optional) -
space (optional)
: A string or a number determining the indentation of nested objects. If it is a number, it indicates the number of spaces to use as white space. If it is a string (such as '\t'), it contains the characters used for indentation. (Optional)
const person = { name: 'John', age: 30 };
const jsonString = JSON.stringify(person);
console.log(jsonString); // Output: {"name":"John","age":30}
Using both JSON.parse()
and JSON.stringify()
together
const jsonString = '{"name": "John", "age": 30}';
const person = JSON.parse(jsonString);
person.age += 1;
const updatedJsonString = JSON.stringify(person);
console.log(updatedJsonString); // Output: {"name":"John","age":31}
In this example, JSON.parse()
is used to convert a JSON string into a JavaScript object, then some manipulation is done on the object, and finally JSON.stringify()
is used to convert the modified object back into a JSON string.