The JavaScript method JSON.parse accepts a JSON string and converts it into an equivalent JavaScript object.
Syntax
Example
JSON.parse(text[, reviver])
Parameters
text : The string to parse as JSON.
reviver: This parameter is not mandatory. It specifies the method by which the value that was initially generated through parsing is modified prior to its return.
Return value
An object corresponding to the given JSON text.
Browser Support
| Chrome | Yes |
|---|---|
| Safari | 4 |
| Firefox | 3.5 |
| Opera | 10.5 |
JavaScript JSON.parse method Examples
Example 1
Let's see a simple example to parse an object.
Example
<script>
//JavaScript to illustrate JSON.parse() method.
var json = '{ "firstName":"ASHU", "lastName":"BHATI", "studentCode":7 }';
var student = JSON.parse(json);
// expected output: ASHU BHATI
document.write(student.firstName + " " + student.lastName);
</script>
Output:
Output
ASHU BHATI
Example 2
Let’s examine an instance of extracting a specific attribute.
Example
<script>
//JavaScript to illustrate JSON.parse() method.
var json = '{ "firstName":"ASHU", "lastName":"BHATI", "studentCode":7 }';
var student = JSON.parse(json);
// expected output: 7
document.write(student.studentCode);
</script>
Output:
Example 3
Let us examine an instance of how to interpret an array of attributes.
Example
<script>
//JavaScript to illustrate JSON.parse() method.
var j = '["C++","JavaScript","Python","HTML"]';
var data = JSON.parse(j);
document.write(data);
//expected output: C++,JavaScript,Python,HTML
</script>
Output:
Output
C++, JavaScript, Python, HTML