user246114
user246114

Reputation: 51621

Safe json parsing with jquery?

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

Upvotes: 6

Views: 4070

Answers (1)

Matthew Flaschen
Matthew Flaschen

Reputation: 284836

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

Upvotes: 5

Related Questions