Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why JSON.parse is not working?

I set the dataType to 'text' because I don't want to Jquery parse my JSON automatically. My code is the following:

var membId = '5';
$('#submitNewDescription').live('click',function(){
    //An ajax request is made to update the DB
    $.ajax({
        url: '../../cgi-bin/qualification.py',
        type: 'POST',
        data: ({newDescription:$('#newDescription').val(),id:membId}),
        dataType: 'text',
        cache: 'false',
        success: function(data){
            json = JSON.parse(data);
            console.log(data);
            console.log(json);
        }
    });
});

And it returns that string: {"error":["ORA-01031 insufficient privileges"]} in both console.log commands. It means that the parse isn't working since it doesn't return a JavaScript object. JSONLint says to me that is a valid JSON.

Anyone has an idea of what is happening?

Thanks

EDIT

I can set to 'json', it is not problem. The problem is that JSON.parse and $.parseJSON should work. Since they are not, I changed 'dataType' to 'json', but the same string is returned. I have no idea what is happening.

like image 943
Frias Avatar asked Mar 14 '11 14:03

Frias


People also ask

Why is JSON parse failing?

The "SyntaxError: JSON. parse: unexpected character" error occurs when passing a value that is not a valid JSON string to the JSON. parse method, e.g. a native JavaScript object. To solve the error, make sure to only pass valid JSON strings to the JSON.

Why JSON parse is not working for a string?

JSON. parse() parses a string as JSON. This string has to be valid JSON and will throw this error if incorrect syntax was encountered.

Is JSON parse blocking or not?

A function that does not accept a callback or return a promise blocks until it returns a value. So yes it JSON. parse blocks. Parsing JSON is a CPU intensive task, and JS is single threaded.

How do I parse a JSON file?

If you need to parse a JSON string that returns a dictionary, then you can use the json. loads() method. If you need to parse a JSON file that returns a dictionary, then you can use the json. load() method.


2 Answers

Probably because you're looking for $.parseJSON instead? Also I beieve jQuery will look at the data and make a best-guess at parsing it before passing it off to the callback. So, if it looks like JSON chances are jQuery's already giving you a JavaScript object back which then can't be re-parsed using JSON.parse/$.parseJSON.

You can also change your dataType field to 'json' and let jQuery do it for you...

like image 142
Brad Christie Avatar answered Sep 18 '22 18:09

Brad Christie


change dataType: 'text' to dataType: "json" and also JSON.parse to $.parseJSON

like image 38
Santosh Linkha Avatar answered Sep 19 '22 18:09

Santosh Linkha