tryJSONParse
Paquete: @tiendana/utils
Parse de JSON seguro que no lanza errores. Si el parsing falla, retorna un valor por defecto en lugar de lanzar excepción.
Características
✅ No lanza errores al parsear
✅ Valor por defecto configurable
✅ Maneja null y undefined
✅ Retorna valor original si no puede parsear
✅ Ideal para localStorage y API responses
✅ Type-safe con TypeScript
Firma
function tryJSONParse(
text?: string | null,
defaultValue?: any
): any
Parámetros
| Parámetro | Tipo | Descripción | Requerido |
|---|---|---|---|
text | string | null | undefined | String JSON a parsear | ❌ |
defaultValue | any | Valor por defecto si el parsing falla | ❌ |
Retorno
Tipo: any
- JSON parseado si el text es válido
defaultValuesi se proporciona y el parsing fallatextoriginal si no se proporciona defaultValue y el parsing falladefaultValuesi text esnull/undefined; sin defaultValue devuelvetext(null/undefined)defaultValuetambién reemplaza a un resultadonulldel parseo ('null')
Ejemplos de Uso
Parse Básico
import { tryJSONParse } from '@tiendana/utils';
const data = tryJSONParse('{"name":"Juan","age":30}');
// { name: 'Juan', age: 30 }
const invalid = tryJSONParse('invalid json');
// 'invalid json' (retorna el texto original)
Con Valor por Defecto
const data = tryJSONParse('invalid json', {});
// {}
const preferences = tryJSONParse(null, { theme: 'light' });
// { theme: 'light' }
const array = tryJSONParse('not an array', []);
// []
LocalStorage
function loadUserPreferences() {
const stored = localStorage.getItem('user-preferences');
return tryJSONParse(stored, {
theme: 'light',
language: 'es',
notifications: true
});
}
// Si localStorage no tiene el dato, retorna el objeto por defecto
const prefs = loadUserPreferences();
API Response
async function fetchUserData(userId: string) {
try {
const response = await fetch(`/api/users/${userId}`);
const text = await response.text();
return tryJSONParse(text, { error: 'Invalid response' });
} catch (error) {
return { error: 'Network error' };
}
}
Form Data
function loadFormData(formId: string) {
const saved = sessionStorage.getItem(`form-${formId}`);
return tryJSONParse(saved, {
name: '',
email: '',
message: ''
});
}
Configuración
interface AppConfig {
apiUrl: string;
timeout: number;
retries: number;
}
function loadConfig(): AppConfig {
const configStr = process.env.APP_CONFIG;
return tryJSONParse(configStr, {
apiUrl: 'https://api.example.com',
timeout: 5000,
retries: 3
});
}
Query Parameters
function getConfigFromUrl() {
const params = new URLSearchParams(window.location.search);
const configParam = params.get('config');
return tryJSONParse(configParam, {});
}
// URL: ?config={"mode":"debug","verbose":true}
const config = getConfigFromUrl();
// { mode: 'debug', verbose: true }
Array Parsing
function loadTags() {
const tagsJson = localStorage.getItem('tags');
return tryJSONParse(tagsJson, []);
}
const tags = loadTags();
tags.forEach(tag => console.log(tag));
Nested Objects
const complexJson = `{
"user": {
"profile": {
"name": "Juan",
"settings": {
"theme": "dark"
}
}
}
}`;
const data = tryJSONParse(complexJson, {});
// Acceso seguro
console.log(data?.user?.profile?.name);
Error Recovery
function parseApiResponse(response: string) {
const parsed = tryJSONParse(response, undefined);
// Sin defaultValue, un JSON inválido devuelve el texto original
if (typeof parsed === 'string') {
console.error('Failed to parse API response');
return { error: true, message: 'Invalid response format' };
}
return parsed;
}
Casos de Uso Comunes
- LocalStorage: Parse seguro de datos de localStorage
- SessionStorage: Recuperar datos de sesión
- API responses: Parse de respuestas de API
- Cookies: Parse de cookies que contienen JSON
- Query parameters: Parse de parámetros de URL
- Configuración: Cargar configuraciones desde variables de entorno
- Form data: Recuperar datos de formularios guardados
- Error recovery: Manejar JSON mal formado sin crashes
Comportamiento con Valores Especiales
Null y Undefined
tryJSONParse(null);
// null (devuelve text tal cual)
tryJSONParse(null, { default: true });
// { default: true }
tryJSONParse(undefined);
// undefined
tryJSONParse(undefined, { default: true });
// { default: true }
JSON Inválido
tryJSONParse('not json');
// 'not json' (retorna el texto original)
tryJSONParse('not json', {});
// {} (retorna defaultValue)
tryJSONParse('{invalid}', []);
// [] (retorna defaultValue)
JSON Válido
tryJSONParse('{"valid":true}');
// { valid: true }
tryJSONParse('[1,2,3]');
// [1, 2, 3]
tryJSONParse('\"string\"');
// 'string'
tryJSONParse('42');
// 42
tryJSONParse('true');
// true
tryJSONParse('null');
// undefined (el resultado null se sustituye por defaultValue, que aquí no existe)
tryJSONParse('null', 5);
// 5
Notas Técnicas
- Performance: O(n) donde n es la longitud del string
- Try-catch: Usa try-catch internamente para manejar errores
- No modifica: No modifica el texto original
- Type-agnostic: Retorna
any, considera usar type assertion o validación - JSON.parse: Usa
JSON.parse()nativo internamente - Fallback chain: Si parse falla → defaultValue → text original. Se usa
??, así que pasarnullcomo defaultValue equivale a no pasarlo: un JSON inválido devuelve el texto original, nonull
Diferencias con JSON.parse
// JSON.parse lanza error
try {
JSON.parse('invalid');
} catch (error) {
// ❌ Debes manejar el error manualmente
}
// tryJSONParse NO lanza error
const result = tryJSONParse('invalid', {});
// ✅ Retorna {} sin crash
Limitaciones
Sin validación de tipo
La función retorna any, lo que significa que no valida el tipo del resultado. Para mayor type safety:
interface User {
name: string;
email: string;
}
const text = '{"name":"Juan","email":"juan@example.com"}';
const user = tryJSONParse(text, {}) as User;
// Mejor: validar el resultado
function isUser(obj: any): obj is User {
return obj && typeof obj.name === 'string' && typeof obj.email === 'string';
}
const parsed = tryJSONParse(text, {});
if (isUser(parsed)) {
// Aquí parsed es User
console.log(parsed.name);
}
Retorna valor original si no hay defaultValue
Si no proporcionas defaultValue y el parsing falla, la función retorna el texto original (que puede no ser lo esperado):
const result = tryJSONParse('invalid json');
// 'invalid json' (string, no objeto)
// Si esperas un objeto, siempre proporciona defaultValue:
const result = tryJSONParse('invalid json', {});
// {} (objeto vacío)
Ver También
- strToNumber - Conversión segura de strings a números
- hasValue - Validar si un valor tiene contenido