Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

jQuery.parseJSON() method

jQuery.parseJSON() method

jQuery Miscellaneous MethodsjQuery Miscellaneous Methods

Example

Parse a JSON string

$

(

function

(

)

{

var

obj

=

jQuery

.

parseJSON

(

'

{"name":"John"}

'

)

;

alert

(

obj

.

name

===

"

John

"

)

;

}

)

Try it »


Definition and Usage

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

**Note:** A JSON string with an incorrect format may cause an exception to be thrown. For example, the following invalid JSON strings:



"{test: 1}"    

//test is the property name, must be enclosed in double quotes



"{'test': 1}"    

//test is the attribute name, must use double quotes (cannot use single quotes)



"'test'" 

//test is the attribute name, must use double quotes (cannot use single quotes)



".1" 

//number must start with a digit; "0.1" will be valid



"undefined"    

//undefined cannot represent a JSON string; null can



"NaN" 

//NaN cannot represent a JSON string; using Infinity directly to represent 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 treats escapes like \t or \n in strings as literal values, resulting in a Tab or a newline.

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

The correct form is as follows (use two backslashes so that \t or \n is not directly escaped by the JS parser):



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

**Note:** Before jQuery 1.9 (excluding 1.9): if an empty string, null, or undefined is passed in, the function returns null rather than throwing an error, even if it is not a valid JSON string.


Syntax

$

.parseJSON( json )

Parameters Description
json String type: The JSON-formatted string to parse and convert into a JS object

jQuery Miscellaneous MethodsjQuery Miscellaneous Methods