jQuery API

jQuery.parseJSON

jQuery.parseJSON( json ) Returns: Object

Description: Takes a well-formed JSON string and returns the resulting JavaScript object.

  • version added: 1.4.1jQuery.parseJSON( json )

    jsonThe JSON string to parse.

Passing in a malformed JSON string may result in an exception being thrown. For example, the following are all malformed JSON strings:

  • {test: 1} (test does not have double quotes around it).
  • {'test': 1} ('test' is using single quotes instead of double quotes).

Additionally if you pass in nothing, an empty string, null, or undefined, 'null' will be returned from parseJSON. Where the browser provides a native implementation of JSON.parse, jQuery uses it to parse the string. For details on the JSON format, see http://json.org/.

Example:

Parse a JSON string.

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

Support and Contributions

Need help with jQuery.parseJSON or have a question about it? Visit the jQuery Forum or the #jquery channel on irc.freenode.net.

Think you've discovered a jQuery bug related to jQuery.parseJSON? Report it to the jQuery core team.

Found a problem with this documentation? Report it to the jQuery API team.

* All fields are required
  • Kip
    Any chance that a jQuery.stringify() or jQuery.toJSON() will ever be added? It's a little odd that jQuery can parse JSON but not encode it.
  • Technoangel
    What to do when Firefox parse it while IE don't (using jQuery 1.4.4)?
  • Technoangel
    Sorry but my bug is more complex than that. The string I send is successfully parsed by $.parseJSON. This is $.ajax which return a parseerror. Does IE cheks the mime-type or something?
  • Technoangel
    This is it. IE (and Chrome) doesn't like to receive JSON under the wrong ContentType header.
  • Widnonly
    How to parse a json to string ?
  • bex
    Use this to turn a JSON object into a string:

    http://code.google.com/p/jquer...
  • spaceduk
    I am unable to parse JSON with a double quote in it...
    var json = '{"test":"ab\"c"}';
    var object = jQuery.parseJSON(json);
    jQuery("div").text(object.test);

    I've checked on http://www.jsonlint.com and {"test":"ab\"c"} is valid, but it doesn't seem to work with parseJSON.

    Also, the following javascript code works fine...
    var json = {"test":"ab\"c"};
    document.write (json.test);

    Is there something I am doing wrong or is it a bug?
  • void
    I think you need to escape \ twice for JSON parser.
    The problem is here: var json = '{"test":"ab\"c"}';
    "ab\"c" is escaped by javascript engine as ab"c and then passed to JSON parser directly.
    If you need to pass ab\"c to a parser, it should be "ab\\\"c".

    This works under my testing:
    var json2 = '{"test":"ab\\\"c"}';
    var object = jQuery.parseJSON(json2);
    alert(object.test);
  • ViperArrow
    If you want to escape a JSON error, instead of letting the browser handle it, you can do something like this:

    try
    {
    result = jQuery.parseJSON( string );
    }
    catch(e)
    {
    // We report an error, and show the erronous JSON string (we replace all " by ', to prevent another error)
    result = jQuery.parseJSON( '{"code":"error","content":"' + e.replace(/"/g, "'") + '"}' );
    }
  • blagus
    How about date objects? I've tryed several combinations (bellow) but none gave back an date object. Should I create a manual parser?

    jQuery.parseJSON(
    '{"birth":"new Date(1978,11,12,8,15,0)"}'
    );

    ...or...

    jQuery.parseJSON(
    '{"z":"new Date(\\"October 13, 1975 21:13:00\\")"}'
    );
  • ViperArrow
    Remove your quotes around "new Date(1978,11,12,8,15,0)". What you are telling your JSON right now is that you want to save "new Date(1978,11,12,8,15,0)" as a string. But JSON can handle more stuff than just strings. (http://www.json.org/ - see value on the right)

    Without the quotes, JSON will understand that you want to save the Date Object as the value for "birth".
  • Guest
    ViperArrow, the Date object has nothing to with JSON. The only legal values are strings, numbers, objects, arrays, true, false and null. Date is neither of those. The reason why new Date() works is because the Javascript evaluates the whole thing directly but that doesn't make it right. JSON is supposed to be language independant and using a hack like that is really bad style.
  • Markus
    Technically speaking, the output of a Date object can be rendered as a number or a string. Furthermore, the string representation of an object in Javascript is the same as an object in JSON since JSON notation is based off Javascript (Hence, JavaScript Object Notation, JSON). So, either way you slice that, it could still be considered valid JSON.

    Also, the very point of using parseJSON when you're exclusively using JS seems rather pointless. you could just as easily have rewritten the above as just:
    {"birth":new Date(1978,11,12,8,15,0)}

    and assigned it directly to the variable. So, the entire argument about "style" is kind of a moot point. The only time it will really matter is if you're sending the data from one language to another. It's only platform independent because libraries have been written to handle the notation in multiple languages. If it weren't for that, JSON would still be limited to just Javascript.

    Furthermore, since the Javascript engine parses the code that way, how is it "wrong"? Personally, I think it's "wrong" to use this method to parse a hardcoded string when you don't have to.
  • Jason
    Hi, I am having trouble getting new Date(123) parsed. There's a parsing error because of malformed JSON. I am using the build in JSON.parse() function of JavaScript. How can it be done?
  • Hammourabi
    Hi,

    I am trying to parse a JSON response which contains HTML data, but parseJSON always rejects me with an Invalid JSON error. How do I have to format the HTML in the json response?

    Thx,

    M.
  • ViperArrow
    Encode your HTML in utf-8.

    In PHP, you can use the native function utf8_encode($string).

    Then you can search the internet to find a JavaScript utf-8 decode function, or just use this one:

    var utf8_decode = function(utftext)
    {
    var string = '';
    var i = 0;
    var c = c1 = c2 = 0;

    while( i < utftext.length )
    {
    c = utftext.charCodeAt(i);

    if( c < 128 )
    {
    string += String.fromCharCode(c);
    i++;
    }
    else if( (c > 191) && (c < 224) )
    {
    c2 = utftext.charCodeAt( i+1 );
    string += String.fromCharCode( ((c & 31) << 6) | (c2 & 63) );
    i += 2;
    }
    else
    {
    c2 = utftext.charCodeAt( i+1 );
    c3 = utftext.charCodeAt( i+2 );
    string += String.fromCharCode( ((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63) );
    i += 3;
    }
    }
    return string;
    };
  • For details on the JSON format, see http://json.org/.
  • var obj = jQuery.parseJSON('{ "status":"error", "msg":"No se encontraron registros de contacto" }');

    if(obj.status == "ok") { return true; } else { alert( obj.msg ); return false; }
  • jQuery.parseJSON(data) tries to use built-in JSON parse, if there are not such it creates new function with body 'return ' + data and returns it's execution result:
    return (new Function('return ' + data))();
  • newb
    Why? I thought the whole point of JSON was that eval(...) could already handle the parsing...

    is the implementation of this function just a forward to eval(...)?