How can I safely use JSON.parse for a string object, which can be a simple string or a string object?

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

I tried JSON.parse (data), but it does not work if the data is a simple string.


EDIT - Selected Solution

Thank you, here is how I solved the problem:

try {
    dataObj = JSON.parse(data);
} catch (err) {
    if (typeof data === "object") {
        dataObj = data;
    } else {
        dataObj = {};
    }
}
+4
source share
3 answers

Use try catch:

var result;
try {
   result = JSON.parse(data);
} catch (err) {
   if (typeof data == 'string') result = data;
   else console.error(err);
}
+3
source

Create yourself a helper function and use it.

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 will become really direct.

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 just call it this:

// string in a variable
var s = "Some non-JSON string";
s.parseJSON();
// string literal
'{"b":true,"n":1}'.parseJSON();
+2

, JSON , , {" ( {), JSON.parse.

.

0
source

Source: https://habr.com/ru/post/1598581/


All Articles