How to check if an answer (date) is a json

Asked

Viewed 2,303 times

4

How can I check if a result (date) coming from an ajax request is a json or not? I tried this code but did not succeed

var obj = $.parseJSON(response);

            if(obj.avatar) {
            } else {
            }
  • The question is confused. Json is a formatted string and the parseJSON of Jquery creates an object structure from this string. Enter the string you have in response. Note: if string is invalid, $.parseJSON throws an exception.

  • Some of the answers solved your problem well. Don’t forget to accept one of them. It would be nice if you could review your questions. I notice that there are many very good answers to them that could be accepted and that you didn’t do it.

2 answers

9

The method parseJSON jQuery raises an exception if JSON is not valid. Therefore:

var obj;
try {
    obj = $.parseJSON(response);
    // use o JSON aqui
} catch(ex) {
    // trate o erro aqui
}

2

A solution with native Javascript suggested in the Soen would be:

function testarJSON (jsonString){
    try {
        var o = JSON.parse(jsonString);
        if (o && typeof o === "object" && o !== null) return o;
    }
    catch (e) { }
    return false;
};

Example:

var jsonValido = '{ "time": "03:53:25 AM", "milliseconds_since_epoch": 1362196405309, "date": "03-02-2013" }';
var jsonInvalido = '"time": "03:53:25 AM", "milliseconds_since_epoch": 1362196405309, "date": "03-02-2013"';

function testarJSON (jsonString){
    try {
        var o = JSON.parse(jsonString);
        if (o && typeof o === "object" && o !== null) return o;
    }
    catch (e) { }
    return false;
};

alert('Nr de JSONs válidos: ' + [jsonValido, jsonInvalido].filter(testarJSON).length);

  • #Revivendo, I had problems with the function it returns me false in this string, why? How to adapt to avoid? Object {response: "sucess_generation"} (index):11 false (is a copy of the console)

  • @user3163662 looks at the console and sees what the server sends. It also puts a console.log(typeof jsonString, jsonString); before you try{ and say what comes.

  • 1 - the Cod you sent me 2 - the string to be checked 3 the error http://imgur.com/XdIZIIIl

  • @user3163662 ok, the object is already translated. So do only if (typeof jsonString == 'object') return jsonString; before the try{.

  • @user3163662 Create a example that reproduces the problem.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.