jQuery.parseJSON()Method

jQuery 杂项方法jQuery Miscellaneous Methods

Examples

Parse a JSON string

$(function () { var obj = jQuery.parseJSON('{"name":"John"}'); alert( obj.name === "John" ); })

Try it yourself »

Definition and Usage

The $.parseJSON() function is used to convert a JSON string in a standard format into the corresponding JavaScript object.

Note:Passing an incorrectly formatted JSON string may cause an exception to be thrown. For example, the following invalid JSON strings:


"{test: 1}"    
//test是属性名称,必须加双引号

"{'test': 1}"    
//test是属性名称,必须用双引号(不能用单引号)

"'test'" 
//test是属性名称,必须用双引号(不能用单引号)

".1" 
//number 必须以数字开头; "0.1" 将是有效的

"undefined"    
//undefined 不能表示一个 JSON 字符串; null可以

"NaN" 
//NaN 不能表示一个 JSON 字符串; 用Infinity直接表示无限也是不允许的

The JSON standard does not allow "control characters" such as tab or newline characters, for example:


// 多数情况下,它会抛出一个错误,因为JS解析器会将字符串中的\t或\n等转义直接视作字面值,起到Tab或换行的效果。
$.parseJSON('{"testing":"1\t2\n3"}')   

The correct syntax should be as follows (use two backslashes to prevent the JS parser from directly escaping \t or \n):

$.parseJSON('{"testing":"1\\t2\\n3"}')  

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 )

Parameters Description
json String type The JSON format string to be parsed and converted into a JS object.


jQuery 杂项方法jQuery Miscellaneous Methods