Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Safe json parsing with jquery?

Tags:

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

like image 989
user246114 Avatar asked Jun 10 '10 16:06

user246114


People also ask

How can you parse JSON via jQuery?

The jQuery parseJSON() method takes a JSON string and returns a JavaScript object. The specified JSON string must follow the strict JSON format. Passing an incorrect string will cause a JS exception. As similar to the above strings, multiple other malformed strings will cause an exception.

Which of the following should you use in order to parse JSON in jQuery?

As of jQuery 3.0, $. parseJSON is deprecated. To parse JSON strings use the native JSON. parse method instead.

What does JSON parse () method do when we initiate an Ajax request?

This parseJSON() Method in jQuery takes a well-formed JSON string and returns the resulting JavaScript value.


1 Answers

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

like image 83
Matthew Flaschen Avatar answered Sep 27 '22 23:09

Matthew Flaschen