jQuery.parseJSON() Method |
Definition and Usage
The $.parseJSON() function is used to convert a JSON string that conforms to the standard format into its corresponding JavaScript object.
Note: Passing a JSON string with incorrect format may cause an exception to be thrown. For example, the following invalid JSON strings:
"{test: 1}" //test is a property name, must be enclosed in double quotes
"{'test': 1}" //test is a property name, must use double quotes (cannot use single quotes)
"'test'" //test is a property name, must use double quotes (cannot use single quotes)
".1" //number must start with a digit; "0.1" would be valid
"undefined" //undefined cannot represent a JSON string; null can
"NaN" //NaN cannot represent a JSON string; directly representing infinity with Infinity is also not allowed
The JSON standard does not allow "control characters" such as tabs or newlines. For example:
// In most cases, it will throw an error because the JS parser will treat escape sequences like t or n in the string as literal values, resulting in a tab or newline effect.
$.parseJSON('{"testing":"1t2n3"}')
The correct way should be as follows (use two backslashes to avoid the JS parser directly escaping t or n):
$.parseJSON('{"testing":"1t2n3"}')
Note: Before jQuery 1.9 (excluding 1.9): If an empty string, null, or undefined is passed, the function will return null instead of throwing an error, even if it is not a valid JSON string.
Syntax
$.parseJSON( json )
| Parameter | Description |
|---|---|
| json | String type. The JSON format string that needs to be parsed and converted into a JS object. |
Example
Parse a JSON string
$(function(){
var obj = jQuery.parseJSON('{"name":"John"}');
alert(obj.name === "John");
})
YouTip