Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

198
Views
Javascript parsing a string that might or might not be valid JSON inside? (extracting an array from a string)

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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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;
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!