JSON.parse()
JSON is usually used to exchange data with the server.
When receiving server data, it is generally a string.
We can use the JSON.parse() method to convert the data into a JavaScript object.
Syntax
JSON.parse(text[, reviver])
Parameter Description:
- text:Required, a valid JSON string.
- reviver:Optional, a function that transforms the result, called for each member of the object.
JSON Parsing Example
For example, we received the following data from the server:
We use the JSON.parse() method to process the above data and convert it into a JavaScript object:
Before parsing, make sure your data is in standard JSON format, otherwise an error may occur.
You can use our online tool to check:https://www.jyshare.com/front-end/53。
After parsing is complete, we can use the JSON data on the webpage:
Example
Try it yourself »
Receiving JSON Data from the Server
We can use AJAX to request JSON data from the server and parse it into a JavaScript object.
Example
Try it yourself »
View server data:json_demo.txt
Receiving JSON Array Data from the Server
If the data received from the server is a JSON array, JSON.parse will convert it into a JavaScript array:
Example
Try it yourself »
View server data:json_demo_array.txt
Exceptions
Parsing Data
JSON cannot store Date objects.
If you need to store a Date object, you need to convert it to a string.
Later, convert the string back into a Date object.
Example
Try it yourself »
We can enable the second parameter of JSON.parse, reviver, a function that transforms the result, called for each member of the object.
Example
Try it yourself »
Parsing Functions
JSON does not allow functions, but you can store a function as a string, and later convert the string back into a function.
Example
Try it yourself »
It is not recommended to use functions in JSON.
Browser Support
All major browsers support the JSON.parse() function:
| Supported | 8.0 | 3.5 | 4.0 | 10.0 |
Older browsers can use third-party libraries for support:https://github.com/douglascrockford/JSON-js
Other Extensions