Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I safely use JSON.parse on a string object that might be a simple string or a string object?

I need to be able to parse a string in an object format or in a plain string format. what is the safest way to do this?

I tried JSON.parse(data) but it does not work in case that data is a plain string.


EDIT - The chosen solution

Thanks to you, this is how I solved the problem:

try {
    dataObj = JSON.parse(data);
} catch (err) {
    if (typeof data === "object") {
        dataObj = data;
    } else {
        dataObj = {};
    }
}
like image 203
Ravit Avatar asked Jul 19 '15 13:07

Ravit


2 Answers

Create yourself a helper function and use that.

function parseValue(value) {
    try
    {
        return JSON.parse(value);
    }
    catch (ex)
    {
        // JSON format was invalid
        // handle errors is you need to
    }

    return value;
}

If you're brave enough you can also extend String.prototype so calling it would become really straight forward.

String.prototype.parseJSON = String.prototype.parseJSON || function() {
    try
    {
        return JSON.parse(this);
    }
    catch (ex)
    {
        // JSON format was invalid
        // handle errors is you need to
    }

    return this;
};

And then you'd simply call it this way:

// string in a variable
var s = "Some non-JSON string";
s.parseJSON();
// string literal
'{"b":true,"n":1}'.parseJSON();
like image 149
Robert Koritnik Avatar answered Nov 14 '22 22:11

Robert Koritnik


Use try catch:

var result;
try {
   result = JSON.parse(data);
} catch (err) {
   if (typeof data == 'string') result = data;
   else console.error(err);
}
like image 31
monkey Avatar answered Nov 14 '22 23:11

monkey