Introduction to the JavaScript JSON parse() Method
JSON (JavaScript Object Notation) is a lightweight data-interchange format that is used to exchange data between different applications. It is based on a subset of the JavaScript programming language and is easy to read and write. The JSON parse() method is used to parse a JSON string and convert it into a JavaScript object.
Syntax of JSON parse() Method
The syntax for the JSON parse() method is:
[dm_code_snippet background=”yes” background-mobile=”yes” slim=”no” line-numbers=”no” bg-color=”#abb8c3″ theme=”dark” language=”php” wrapped=”no” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]
JSON.parse(text[, reviver])
[/dm_code_snippet]
Where:
- text – The string to be parsed as JSON.
- reviver – Optional. A function that transforms the results.
Return Value of JSON parse() Method
The JSON parse() method returns the resulting JavaScript object.
Examples of JSON parse() Method
Let’s look at some examples of the JSON parse() method.
Example 1: Parsing a JSON string
In this example, we are parsing a JSON string and converting it into a JavaScript object.
[dm_code_snippet background=”yes” background-mobile=”yes” slim=”no” line-numbers=”no” bg-color=”#abb8c3″ theme=”dark” language=”php” wrapped=”no” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]
let jsonStr = '{"name":"John", "age":30, "city":"New York"}'; let jsonObj = JSON.parse(jsonStr); console.log(jsonObj);
[/dm_code_snippet]
This will output the following result:
[dm_code_snippet background=”yes” background-mobile=”yes” slim=”no” line-numbers=”no” bg-color=”#abb8c3″ theme=”dark” language=”php” wrapped=”no” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]
{ name: "John", age: 30, city: "New York" }
[/dm_code_snippet]
Example 2: Parsing a JSON string with the reviver function
In this example, we are parsing a JSON string and transforming the result using the reviver function.
[dm_code_snippet background=”yes” background-mobile=”yes” slim=”no” line-numbers=”no” bg-color=”#abb8c3″ theme=”dark” language=”php” wrapped=”no” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]
let jsonStr = '{"name":"John", "age":30, "city":"New York"}'; let jsonObj = JSON.parse(jsonStr, (key, value) => { if (key === 'age') { return value * 2; } else { return value; } }); console.log(jsonObj);
[/dm_code_snippet]
This will output the following result:
[dm_code_snippet background=”yes” background-mobile=”yes” slim=”no” line-numbers=”no” bg-color=”#abb8c3″ theme=”dark” language=”php” wrapped=”no” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]
{ name: "John", age: 60, city: "New York" }
[/dm_code_snippet]
Conclusion
In this tutorial, we learned about the JSON parse() method and how to use it to parse a JSON string and convert it into a JavaScript object. We also saw how to use the reviver function to transform the results.