Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

199
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda