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 on the GitHub issue tracker

  • Name

    I’m happy to see this method, since I’m looking to drop Crockford’s json2 library from our js package altogether if I can (simply to reduce filesize), but there doesn’t seem to be a “stringify” counterpart to parseJSON. Am I mistaken? In any case, I’m wondering if parseJSON is in fact identical to JSON.parse. Can someone clarify? Thanks.

    • dyu

      How would you serialize/write json string from js objects without json2.js?

      • Matt

        Yeah is there a simple way to stringify?

      • Anonymous

        I’m joining to the question. This function can parse JSON string, but what jQuery function can do the opposite thing?

        • http://www.learningjquery.com/ Karl Swedberg

          There currently is no jQuery method to “stringify a JSON object. So, the others are correct: you would need to use json2.js for that.

          • Anonymous

            But if we have to use json2.js that already includes JSON.parse method what the sense of using jQuery.parseJSON method?

          • Bob

            Well, if it’s already built into jQuery, use jQuery.parseJSON, and json2.js to “stringify” JSON, at least until it too is built into jQuery. The way I see it, this helps people who only need to parse JSON to keep the number of files they need down.

        • http://bexhuff.com bex

          To turn a JSON object into a string, use the jquery.json.2-2 plugin:

          http://code.google.com/p/jquery-json/

          This is useful if you want to POST JSON objects back to a server that might prefer an encoded string instead.

      • r.

        The question is why is there not a stringify equivalent in jQuery, if they implemented the parsing half of json2.js.

  • 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(…)?

    • Bob

      Some browsers have a native method of parsing JSON which is supposed to be faster than eval. Maybe that’s what parseJSON is doing. Devs please clear this.

    • http://claimid.com/zefciu zefciu

      Using eval isn’t very secure. The eval’d input can have side effects, so if you try to parse JSON from untrusted source, you shouldn’t use it. String parsed by JSON-only evaluation function like this, is just data. The process of parsing cannot do any harm to your script.

      • Anonymous

        And the eval is slow.

    • Anonymous

      Eval is slow the native JSON.parse is way faster. However, not all browsers support the native JSON object/ class. Like mobile Safari doesn’t currently support. JSON.parse so this jquery method
      detects this native parsing support.

    • ,jJ’

      No.. it used to be the case, but for various reasons (security for one) JSON is defined as a strict subset of JavaScript literal syntax and parseJSON checks for the correct format…

  • http://www.ixti.ru/ Aleksey V. Zapparov AKA ixti

    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))();

  • http://mcnallydevelopers.com Paulo McNally

    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; }

  • 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.

    • http://www.learningjquery.com/ Karl Swedberg

      For details on the JSON format, see http://json.org/.

    • 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 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;
      };

  • Anonymous

    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?

  • 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, “‘”) + ‘”}’ );
    }

  • Anonymous

    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);

  • http://www.royleban.com Roy Leban

    The documentation is misleading — in some situations, malformed JSON as described will be parsed properly. This happens if the browser has no JSON parser and the evaluation happens through defining a function from the string (see source code of parseJSON to see what I mean). Documentation should say “may” throw an exception.

  • Widnonly

    How to parse a json to string ?

  • http://twitter.com/aponxi Logan

    How would you check if somelinksdomain is one of those in that array?

    var services = {
    'youtube': ['http://www.youtube.com', youtube.com],
    'domain': ['domain.com', 'http://www.domain.com']
    };

    This is what i have working with a single domain string (like 'youtube' : 'http://www.youtube.com')

    $.each(services, function(name, domain) {
    if (somelinksdomain == domain) {
    $('#' + name).append(name+'
    ' +somelinksfullurl);

    }
    All i need is to match the arrays instead of the string so that it can search all the domains recorded, instead of just one for each. I appreciate the help

  • http://twitter.com/anes_pa Anes P.A

    Hi Pals,
    I am a newbie in json , so i need your help to parse the json data below using jQuery,Help me

    {“access_servers”:[{"id":"2","servername":"anes.admod.net","ip_address":"10.10.3
    .28","ssh_port":"22","description":"","enable_ssh":"Y","cp_id":"0","dc_id":"0",
    "servergroup_id":"1","groupname":"test"},{"id":"1","servername":"neseema.admod.
    net","ip_address":"10.10.3.12","ssh_port":"22","description":"","enable_ssh":"Y"
    ,"cp_id":"0","dc_id":"0","servergroup_id":"1","groupname":"test"}],”rows_server”
    :2,”group”:[{"id":"1","name":"test","description":"","created":null,"modified":
    "2010-11-08
    12:00:43"}],”user”:{“id”:”1″,”firstname”:”Ezeelogin”,”created”:”0000-00-00
    00:00:00″,”lastname”:”Administrator”,”email”:”",”usergroup_id”:”1″,”status”:”1″,
    “ip_enable”:”N”,”priv”:”0″},”server_group_name”:{“1″:”test”},”userarray”:{“id”:
    “1″,”firstname”:”Ezeelogin”,”created”:”0000-00-00
    00:00:00″,”lastname”:”Administrator”,”email”:”",”usergroup_id”:”1″,”status”:”1″,
    “ip_enable”:”N”,”priv”:”0″},”usergroupid”:”1″,”offset”:0,”server_details”:”N”,
    “sshport”:”22″,”sshuser”:”root”,”pagelinks”:”",”totrows”:”2″,”limitvalue”:”10″,
    “current”:”server”,”sort_by”:”servername”,”sort_order”:”ASC”,”controlpanels”:{
    “1″:”Cpanel/WHM”,”2″:”Plesk”,”3″:”Webmin”,”4″:”Webmin
    secure”},”datacenters”:[]}

    Thankfully
    Anes

  • 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.

  • http://amskape.myopenid.com/ Anes

    Do any one Demonstrate the Usage of eval() for json parsing ?

  • 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.