Deep Tech Point
first stop in your tech adventure
Home / Javascript
How to test if a string is json or not
February 19, 2021 | Javascript

Maybe you have an issue with a server, which is sometimes returning either a JSON string with some useful data, and at other times server returns an error message string, which is produced by the PHP function mysql_error(). A simple solution to this problem would be to test whether this data is a JSON string or an error message.

A straightforward answer to a question on how to test if a string is JSON or not would be to use JSON.parse function isJson(str), like so:

function isJson(str) {
    try {
        JSON.parse(str);
    } catch (e) {
        return false;
    }
    return true;
}

If you want to check the logic of a string – whether it is a JSON string or not, you should use the JSON.parse()method with a few variations:
JSON.parse() method will parse a JSON string, and then construct the JavaScript value or object, which is specified by the string. You could provide a reviver function to change a resulting object before it’s returned. As mentioned below, the reviver function is not required.

The syntax of JSON.parse looks like this:

JSON.parse(text[, reviver])

Text as a parameter is required. In this case text specifies the string, which you will parse as JSON.
Reviver, however, is optional as a parameter. Reviver will specify how the function will produce the original value and transform it before it is returned.

There are a few more approaches you could use when testing if a string is JSON or not, of course depending on the goal you’re trying to achieve.

hasJsonStructure()
hasJsonStructure() is useful if you want to check if some data or text has proper JSON interchange format, like so:

function hasJsonStructure(str) {
    if (typeof str !== 'string') return false;
    try {
        const result = JSON.parse(str);
        const type = Object.prototype.toString.call(result);
        return type === '[object Object]' || type === '[object Array]';
    } catch (err) {
        return false;
    }
}

hasJsonStructure('true');  // false
hasJsonStructure('{"x":true}'); // true
hasJsonStructure('[1, false, null]'); // true

safeJsonParse()
safeJsonParse() function is useful if you want to be careful when parsing some data to a JavaScript value.

function safeJsonParse(str) {
    try {
        return [null, JSON.parse(str)];
    } catch (err) {
        return [err];
    }
}

const [err, result] = safeJsonParse('[Invalid JSON}');
if (err) {
    console.log('Failed to parse JSON: ' + err.message);
} else {
    console.log(result);
}

SOURCE:
https://stackoverflow.com/questions/9804777/how-to-test-if-a-string-is-json-or-not