Home > Net >  Javascript parsing a string that might or might not be valid JSON inside? (extracting an array from
Javascript parsing a string that might or might not be valid JSON inside? (extracting an array from

Time:05-12

I have a property of an object which is always a string. The string however might just be regular characters or it might contain a stringified array of values.

If its a regular string of characters then I want to just pass the value through but if its an array, then I want to do some further processing on it in its array form.

I can use JSON.parse(myValue) which is great for extracting an array but throws an error if its a regular string.

I could maybe do something like:

let extractedVal = '';

try {
  extractedVal = JSON.parse(myValue)
} catch (e) {
  extractedVal = myValue
}

but this doesn't feel right as the let variable feels messy and the try/catch feels like its not being used correctly as I'm not doing anything with the error etc... .

Is there a better way or a suggested best practice to achieve this?

CodePudding user response:

Using a try/catch in this situation is just fine. I wouldn't assign an initial value to the extractedVal variable, though, since you're reassigning it in both branches, just remove that = '' initializer.

You could change it slightly:

let extractedVal = value;
try {
    extractedVal = JSON.parse(extractedVal);
    // ...more processing here...
} catch {
    // ...ignore...
}

but frankly I think your original is just as clear, here with a couple of tweaks:

let extractedVal;
try {
    extractedVal = JSON.parse(value);
    // ...more processing here...
} catch {
    extractedVal = value;
}
  • Related