How To Use JSON.parse() and JSON.stringify()
How to Use JSON.parse() and JSON.stringify()
JSON (JavaScript Object Notation) is a lightweight data interchange format that is easy to read and write. It is widely used in web applications to transmit data between client and server.
JSON.parse()
The JSON.parse() method is used to parse a JSON string and convert it into a JavaScript object.
Syntax:
JSON.parse(text[, reviver])
The text parameter is the JSON string to parse. The optional reviver parameter is a function that can filter and transform the resulting object.
Example:
const jsonStr = '{"name":"John", "age":30, "city":"New York"}';
const obj = JSON.parse(jsonStr);
console.log(obj.name); // Output: John
JSON.stringify()
The JSON.stringify() method is used to convert a JavaScript object into a JSON string.
Syntax:
JSON.stringify(value[, replacer[, space]])
The value parameter is the JavaScript object to convert. The optional replacer parameter is a function that can filter and transform the resulting JSON string. The optional space parameter is used to add whitespace for readability.
Example:
const obj = {name: "John", age: 30, city: "New York"};
const jsonStr = JSON.stringify(obj);
console.log(jsonStr); // Output: {"name":"John","age":30,"city":"New York"}
With these methods, you can easily convert data between JSON format and JavaScript objects. They are useful for working with APIs and other web services that transmit data in JSON format.
Keywords: JSON.parse(), JSON.stringify(), JavaScript object, JSON string, web applications, client, server, parse, convert, filter, transform, whitespace, readability, APIs, web services.
Комментарии
Отправить комментарий