6

I am using jquery with json. My client pages generate json, which I store on my server. The clients can then fetch the json back out later, parse, and show it.

Since my clients are generating the json, it may not be safe. I think jquery uses eval() internally. Is that true? Is there a way to use the native json parsers from the browsers where available, otherwise fall back to manual parsing if not? I'm new to jquery so I don't know where I'd insert my own parsing code. I'm doing something like:

$.ajax({
    url: 'myservlet',
    type: 'GET',
    dataType: 'json',
    timeout: 1000,
    error: function(){
        alert('Error loading JSON');
    },
    success: function(json){
        alert("It worked!: " + json.name + ", " + json.grade);
    }
});

so in the success() method, the json object is already parsed for me. Is there a way to catch it as a raw string first? Then I can decide whether to use the native parsers or manual parsing (hoping there's a jquery plugin for that..).

The articles I'm reading are all from different years, so I don't know if jquery has already abandoned eval() already for json,

Thank you

user246114
  • 50,223
  • 42
  • 112
  • 149

1 Answers1

5

The latest version has jQuery.parseJSON. It will use native JSON in browsers that have it. For older ones, it will do a regex sanity check, then use new Function() (basically eval).

Since you specified 'json' as the dataType, it will use parseJSON here. This is handled in the internal httpData function

Matthew Flaschen
  • 278,309
  • 50
  • 514
  • 539
  • but if the browser does not support it, then does it fall back to using eval()? If so, I'd be exposing my users to risk? Thanks – user246114 Jun 10 '10 at 16:20
  • It does use `new Function` (basically `eval`) if native JSON isn't available, but only after sanity-checking it with regex from JSON.org (see http://www.json.org/json2.js). This *should* prevent script injection. – Matthew Flaschen Jun 10 '10 at 16:23
  • Ah great. But how do we use jQuery.parseJSON() with the $.ajax({}) example above? By the time the function returns, the response has already been parsed by jQuery, right? – user246114 Jun 10 '10 at 16:29
  • 1
    Latest jQuery will use parseJSON internally. . – Matthew Flaschen Jun 10 '10 at 16:41