Zum Hauptinhalt springen
Echtzeit-Radar & Feeds
Alle RSS Feeds ➔
👥 Community & Social
Windows Tipps & SecurityGrafikkarte vor Überhitzung schützen: So geht’s(25.09.2026 um 08:00 Uhr)
••••••••••
Windows Tipps & SecurityGrafikkarte vor Überhitzung schützen: So geht’s(25.09.2026 um 08:00 Uhr)
••••••••••
Intelligence View
⚡ tsecurity.de Intelligence

Formatear y validar JSON en JavaScript: JSON.stringify(), errores comunes y casos límite

JSON es el formato de intercambio de datos más usado en desarrollo web. Pero JSON.stringify() y JSON.parse() tienen matices que sorprenden incluso a desarrolladores con años de experiencia. Formateo con indentación const da…

0
↗ Quelle (dev.to)
Reagiere als Erste:r — dein Feedback zählt!

JSON es el formato de intercambio de datos más usado en desarrollo web. Pero JSON.stringify() y JSON.parse() tienen matices que sorprenden incluso a desarrolladores con años de experiencia.






Formateo con indentación






const data = { name: 'ToolRapido', tools: ['NIF', 'QR', 'UUID'], active: true };

// Compacto (por defecto)
JSON.stringify(data);
// '{"name":"ToolRapido","tools":["NIF","QR","UUID"],"active":true}'

// Indentado con 2 espacios
JSON.stringify(data, null, 2);
// {
// "name": "ToolRapido",
// "tools": ["NIF", "QR", "UUID"],
// "active": true
// }

// Indentado con tabuladores
JSON.stringify(data, null, '\t');









Validar JSON sin try/catch en cada sitio






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

// Versión que devuelve el error
function parseJSON(str) {
try {
return { ok: true, data: JSON.parse(str) };
} catch (err) {
return { ok: false, error: err.message };
}
}

const result = parseJSON('{"broken": json}');
result.ok; // false
result.error; // 'Unexpected token j in JSON at position 12'









Tipos que JSON.stringify() ignora o transforma



Esto sorprende a muchos:




JSON.stringify({
fn: () => {}, // undefined (se omite)
sym: Symbol('x'), // undefined (se omite)
undef: undefined, // undefined (se omite)
nan: NaN, // null
inf: Infinity, // null
date: new Date(), // string ISO
regexp: /regex/, // {} ← TRAMPA
map: new Map([['a', 1]]), // {} ← TRAMPA
set: new Set([1, 2]), // [] ← TRAMPA
});






Para serializar Map y Set:




function replacer(key, value) {
if (value instanceof Map) {
return { __type: 'Map', entries: [...value.entries()] };
}
if (value instanceof Set) {
return { __type: 'Set', values: [...value] };
}
return value;
}

function reviver(key, value) {
if (value?.__type === 'Map') return new Map(value.entries);
if (value?.__type === 'Set') return new Set(value.values);
return value;
}

const data = { myMap: new Map([['a', 1]]) };
const json = JSON.stringify(data, replacer, 2);
const back = JSON.parse(json, reviver);
back.myMap instanceof Map; // true









El replacer para filtrar campos






// Solo incluir campos específicos
JSON.stringify(user, ['name', 'email'], 2);

// Excluir campos sensibles
function omitSensitive(key, value) {
const sensitive = ['password', 'token', 'secret'];
if (sensitive.includes(key)) return undefined;
return value;
}
JSON.stringify(user, omitSensitive, 2);









Clonar objetos con JSON






// Forma rápida (limitada — pierde funciones, fechas, etc.)
const clone = JSON.parse(JSON.stringify(obj));

// Forma moderna y correcta
const clone = structuredClone(obj); // soporta Date, Map, Set, etc.






structuredClone() está disponible en Node 17+ y todos los navegadores modernos.






Diferencias entre JSON y JSON5



JSON5 es un superconjunto de JSON que permite comentarios, comas finales y más:




{
// Comentarios
name: 'sin comillas en keys',
trailing: 'coma',
hex: 0xFF,
multiline: "primera línea \
segunda línea",
}






JSON5 es útil para archivos de configuración pero no para APIs (usar siempre JSON estándar en APIs).






Herramienta online



Si necesitas formatear o validar un JSON rápidamente durante el desarrollo, puedes usar este formateador de JSON gratuito que funciona en el navegador con resaltado de errores.






Conclusión




  • Usa JSON.stringify(data, null, 2) para formateo legible


  • Map, Set, RegExp y funciones no se serializan como esperas — planifica cómo manejarlos


  • structuredClone() es mejor que JSON.parse(JSON.stringify()) para clonar objetos

  • Centraliza el parseo en una función que devuelva { ok, data, error } para manejar errores limpiamente

1. Sofort-Triage & Abwehrmaßnahmen

SOC Incident Playbook: Vulnerability Remediation & Verification
Syntax validiert (0 Fehler)
title: Detect Exploitation - Formatear y validar JSON en JavaScript: JSON.stringify(), errores comunes y casos límite
id: 0323f55c-983d-4558-b6c6-65cf6f78c0a5
status: experimental
description: Automatisch generierte SIEM-Erkennungsregel basierend auf CTI Intelligence
references:
  - https://tsecurity.de/
author: iShareStuff CTI Automated Detection Engine
date: 2026-09-27
logsource:
  category: network_connection
  product: any
detection:
  selection:
      CommandLine|contains:
        - 'exploit'
  condition: selection
falsepositives:
  - Legitime administrative Zugriffe oder Penetrationstests
level: high
tags:
  - attack.initial_access
Syntax validiert (0 Fehler)
rule CTI_Threat_Indicator {
    meta:
        author = "iShareStuff CTI Automated Detection Engine"
        date = "2026-09-27"
        description = "YARA Signature for "
    strings:
        $str = "Formatear y validar JSON en Ja" ascii wide
    condition:
        any of them
}
Syntax validiert (0 Fehler)
index=security sourcetype IN ("cisco:asa", "pan:traffic", "zeek_conn", "suricata", "WinEventLog:Security")
("Formatear y validar JSON en JavaScript J")
| stats count earliest(_time) as first_seen latest(_time) as last_seen by src_ip, dest_ip, dest_host, signature
| eval first_seen=strftime(first_seen, "%Y-%m-%d %H:%M:%S"), last_seen=strftime(last_seen, "%Y-%m-%d %H:%M:%S")
| sort - count
Syntax validiert (0 Fehler)
message: "*Formatear y validar JSON en JavaScript J*"
Syntax validiert (0 Fehler)
CommonSecurityLog
| where Message has "Formatear y validar JSON en JavaScript J"
| summarize EventCount = count(), FirstSeen = min(TimeGenerated), LastSeen = max(TimeGenerated) by SourceIP, DestinationIP, DestinationPort, Activity
| extend DetectionRule = "iShareStuff-CTI-Compiled"
| sort by EventCount desc

2. Cyber Threat Intelligence & Forensik

🎯
MITRE ATT&CK Matrix Navigator 14 Taktiken
Reconnaissance
-
Resource Development
-
Initial Access
Execution
Persistence
-
Privilege Escalation
Defense Evasion
Credential Access
-
Discovery
-
Lateral Movement
-
Collection
-
Command and Control
Exfiltration
-
Impact
tsecurity.de Cognitive Threat RAG
Fokus-Vektor:

Analyse für identifizierte Bedrohung auf Basis von Live-CTI (ENISA EUVD): CVSS 0.0 · EPSS 0.0% · CISA KEV: nein. Handlungsableitung aus den verlinkten Hersteller-Quellen.

🛡️ Angriffsfläche & Exposure

Netzwerk/Remote-Zugriff ohne Vorauthentifizierung möglich.

⚡ Empfohlene Sofortmaßnahmen
  • 1. Perimeter-Inspektion: Relevante Portfreigaben und exponierte Endpunkte unverzüglich scannen.
  • 2. Patch-Applikation: Hersteller-Hotfix einspielen oder betroffene Daemons in isolierte DMZ-Segmente überführen.
  • 3. Telemetrie & EDR-Alerts: Prozessaufrufe und Child-Processes auf anomale Shell-Spawns überwachen.
Ähnliche Beiträge
🔍 Verwandte News

Auch interessante Nachrichten Formatear y validar JSON en JavaScript: JSON.stringify(), errores comunes y casos límite

Thematisch verwandte Begriffe: Formatear, validar, JSON, JavaScript · 6 Treffer

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

💬 Kommentare werden geladen…
Zum Aktualisieren ziehen
ZERO-DAY CVE-2026-100620 | Capgo CLI (npm package @capgo/cli) through 7.98.2 is affected by an ove…
Advisory →
tsecurity.de Icon
Offline-Lesen, Eilmeldungen & 0ms Ladezeit

Installiere tsecurity.de direkt auf deinen Home-Bildschirm für das ultimative Vollbild-Magazinerlebnis ohne Browser-Leisten.

Nächster Beitrag