Recursos · 81
Extracción con IA: validar JSON antes de integrarlo
Separar análisis sintáctico, esquema, evidencia documental y reglas de negocio para convertir documentos en datos utilizables.
Actualizado · 8 min
Lo que esta guía ayuda a lograr
- Definir el contrato del resultado
- Vincular cada valor con una evidencia
- Validar en un orden explícito
- Probar documentos difíciles
- Preparar recuperación y corrección
Comprobación rápida
- ¿Puede un JSON válido contener un error?
- ¿Debe un campo ausente convertirse en cero?
- ¿Cuándo se necesita revisión humana?
Método paso a paso
- 1
Definir el contrato del resultado
Enumere los campos necesarios, sus tipos, unidades y estados de ausencia. JSON Schema distingue propiedades descritas y campos obligatorios: declarar una propiedad no la convierte en obligatoria. Decida si se admiten campos adicionales. Conserve la versión del esquema en cada lote y evite recoger campos sin una finalidad.
Entregable: esquema versionado y ejemplos aceptados o rechazados.
- 2
Vincular cada valor con una evidencia
Solicite referencias a página, pasaje o celda para los valores que desencadenan una acción. Permita un estado desconocido cuando falte información. Un importe con el tipo correcto puede pertenecer a otro documento; una fecha plausible puede ser la de emisión en lugar del vencimiento.
Entregable: relación entre campo, fuente y regla de interpretación.
- 3
Validar en un orden explícito
Compruebe primero el análisis JSON, después el esquema y finalmente reglas de negocio: moneda permitida, identificador existente, suma de líneas y cronología. La conformidad con el esquema no garantiza exactitud ni autorización para escribir en un sistema. Bloquee la acción hasta reunir sus condiciones.
Entregable: clases de error y decisiones de aceptación separadas.
- 4
Probar documentos difíciles
Incluya tablas divididas, varios idiomas, valores contradictorios, documentos vacíos e instrucciones hostiles dentro del texto. Pruebe rechazos, truncamiento y reintentos. Mantenga casos de evaluación independientes del ajuste y compare errores por campo, sin convertir una tasa global en garantía.
Entregable: conjunto de referencia y errores críticos.
- 5
Preparar recuperación y corrección
Relacione documento, versión del modelo, esquema y resultado con un identificador de procesamiento. Un reintento no debe crear dos registros. Conserve la justificación de las correcciones humanas y localice las salidas derivadas. Evite copiar documentos completos en registros sin necesidad.
Entregable: procedimiento de corrección y reintento controlado.
Del resultado legible a la acción autorizada
Superar una comprobación no sustituye la siguiente. Detenga el proceso si falta una condición necesaria.
Analizar JSON
¿La respuesta está completa y puede analizarse?
Validar el contrato
¿Tipos, campos, unidades y ausencias corresponden al esquema?
Verificar valores
¿Las fuentes y reglas de negocio respaldan los valores?
Autorizar la acción
¿Se cumplen identidad, alcance y condiciones de escritura?
Ejemplo ficticio: pasan análisis y esquema, pero dos importes se contradicen. La escritura queda bloqueada y el registro pasa a revisión.
Caso de aceptación reproducible
Ejemplo ficticio: estos datos no describen clientes ni resultados observados.
Ver datos del caso
{
"schema": {
"type": "object",
"required": [
"amount"
],
"properties": {
"amount": {
"type": "number"
}
}
},
"output": {
"amount": "12.50"
}
}Decisión esperada
"12.50" es texto, no number. Rechace o corrija explícitamente antes de integrar.
Variantes ficticias para comprobar
Un entero grande cambia al leer y volver a escribir el JSON.
Compare el valor original y el leído, por ejemplo 9007199254740993. Algunos tratamientos en binario64 redondean este entero. Elija una representación exacta adecuada al contrato antes de integrarlo.
El productor valida con la versión 1, pero el destinatario espera la versión 2.
Asocie el resultado a una versión explícita del contrato y compruebe su compatibilidad con el destinatario. Superar un esquema anterior no valida automáticamente la nueva versión.
El lote es válido, pero la respuesta figura interrumpida.
Conserve el estado incompleto. Compruebe el fin de generación y la cobertura esperada antes de integrar el lote como resultado completo.
Evidencias que conservar
- Respuesta original protegida y estado de finalización.
- Versión del esquema y errores de validación localizados.
- Comprobaciones de negocio y cobertura del lote.
Referencia complementaria : IETF — RFC 8259, number interoperability [EN]
Procedimiento de verificación
- Fije campos requeridos, tipos y valores permitidos.
- Valide importe textual contra esquema numérico.
- Conserve ruta del error y corrección explícita. Añada un resultado conforme al esquema con un valor contrario al documento fuente; distíngalo de una extracción verificada.
Hoja de cálculo reutilizable
Complete con sus observaciones autorizadas. Estos campos son una plantilla de trabajo, no resultados observados.
| Campo | Información a registrar |
|---|---|
| Contrato | Campos, tipos, unidades, ausencia y versión del esquema |
| Evidencia | Documento y pasaje de cada campo decisivo |
| Validación | Análisis JSON, esquema, reglas de negocio y motivo del rechazo |
| Recuperación | Identificador de procesamiento, duplicados evitados y correcciones propagadas |
Ejemplo trabajado ficticio
Situación ilustrativa
Ejemplo ficticio: un extractor encuentra dos totales de factura y selecciona el importe sin impuestos, pero el conector espera el importe a pagar.
Decisión y pruebas esperadas
El esquema acepta el número; la conciliación de líneas y moneda bloquea la escritura y envía el documento a revisión.
Distinguir los mecanismos
| Mecanismo | Propósito | Verificación o limitación |
|---|---|---|
| JSON legible | Permitir el análisis sintáctico | No valida campos esperados ni significado |
| Conformidad del esquema | Comprobar tipos y restricciones | No demuestra fidelidad al documento |
| Conciliación de negocio | Comprobar utilidad y coherencia | Necesita reglas y referencias explícitas |
Indicadores de gestión
| Indicador | Qué mide | Primera acción |
|---|---|---|
| Exactitud por campo | Valores correctos entre los campos evaluables | Priorizar errores que cambien una acción |
| Abstención útil | Casos sin decisión por falta de evidencia | Revisar la cola sin incentivar valores inventados |
| Duplicados al reintentar | Registros repetidos para una operación | Corregir la deduplicación |
Errores comunes
- No valida campos esperados ni significado
- No demuestra fidelidad al documento
- Necesita reglas y referencias explícitas
Preguntas frecuentes
¿Puede un JSON válido contener un error?
Sí. Puede cumplir sintaxis y esquema y contener un importe, identidad o fecha incorrectos. Contraste los valores decisivos con sus fuentes.
¿Debe un campo ausente convertirse en cero?
Solo si el contrato asigna ese significado a cero. En otro caso utilice el estado de ausencia previsto; los valores inventados alteran los cálculos.
¿Cuándo se necesita revisión humana?
Cuando una contradicción, evidencia ausente o error crítico quede fuera del alcance aceptado. Defina esos casos antes de procesar lotes.
IA: comprobar un resultado JSON
Las notas detalladas de esta edición están disponibles en inglés.
Schema-valid JSON can still contain false values
AI extraction turns a document into usable fields. Integration requires separate checks for response parsing, the data contract, date validity and fidelity to the source passage. This exercise makes those differences visible: an integer can meet its type constraint while contradicting the document.
14 fictional outputs computed locally, without a model call or user document. Reference DOC-TRAIN-01, page 2, states “Count: 12” on 20 October 2026. No reference is supplied for DOC-TRAIN-02. Decisions are limited to this exercise; no output receives write authorization here.
The comparison reference is visible
{
"document_id": "DOC-TRAIN-01",
"page": 2,
"status": "observed",
"count": 12,
"observed_on": "2026-10-20",
"quote": "Count: 12"
}This small object is the exercise’s complete reference, not a real document or external provenance evidence. Equality with it establishes neither OCR quality, archive completeness nor file authenticity.
The JSON Schema 2020-12 contract
The contract requires six fields and rejects extra properties. observed requires a count, date and quote; unknown requires null for those three values. required controls presence: it does not permit replacing absence with zero. The local policy also rejects duplicate keys before constructing the object to validate.
The JSON Schema 2020-12 contract
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"title": "Fictional document observation v1",
"type": "object",
"additionalProperties": false,
"required": [
"document_id",
"page",
"status",
"count",
"observed_on",
"quote"
],
"properties": {
"document_id": {
"enum": [
"DOC-TRAIN-01",
"DOC-TRAIN-02"
]
},
"page": {
"type": "integer",
"minimum": 1
},
"status": {
"enum": [
"observed",
"unknown"
]
},
"count": {
"type": [
"integer",
"null"
],
"minimum": 0
},
"observed_on": {
"type": [
"string",
"null"
],
"format": "date"
},
"quote": {
"type": [
"string",
"null"
],
"minLength": 1
}
},
"allOf": [
{
"if": {
"properties": {
"status": {
"const": "observed"
}
},
"required": [
"status"
]
},
"then": {
"properties": {
"count": {
"type": "integer"
},
"observed_on": {
"type": "string"
},
"quote": {
"type": "string"
}
}
},
"else": {
"properties": {
"count": {
"type": "null"
},
"observed_on": {
"type": "null"
},
"quote": {
"type": "null"
}
}
}
}
]
}Draft202012Validator checks the schema. Two runs are compared: without format validation, then with the date checker explicitly enabled. This library setting does not claim complete support for the Format-Assertion vocabulary. No remote schema reference is retrieved during computation.
Python 3.12.14 · python-jsonschema 4.26.0 · Draft 2020-12 · FormatChecker: date
Six distinctions to preserve in the connector
| Distinction | Effect in this exercise | Example |
|---|---|---|
| Syntax / key uniqueness | A parser may accept a duplicate; the local profile rejects it rather than silently overwrite a value. | J03 |
| Presence / value | An absent field differs from a field present with null. | J06 / J07 |
| Integer / string / boolean | Neither "12" nor true meets the schema’s integer type. No silent coercion is applied. | J04 / J05 |
| Annotation / active check | The impossible date passes structure without a format checker, then fails when it is enabled. | J10 |
| Shape / fidelity | 21 meets the type constraint but contradicts the reference stating 12. | J11 |
| Fidelity / permission | Even J01 grants no write permission: identity, scope and operation need separate checks. | J01 |
14 outputs: read the reason before retrying
Each disclosure contains the exact received text and computed checks. “Not run” is not a pass. Syntax, duplicate, schema or date errors stop later stages. Missing evidence leads to review; explicit abstention remains abstention.
J01 · Matching within the exercise scope
Exact fictional output text
{"document_id":"DOC-TRAIN-01","page":2,"status":"observed","count":12,"observed_on":"2026-10-20","quote":"Count: 12"}- JSON syntax
- Passed
- Unique keys
- Passed
- Schema without format checking
- Passed
- Schema with date checking
- Passed
- Match to the reference
- Passed
Ready for the next review, without write permission
Fields match the local reference. This only makes the result ready for the next review; no permission or business operation has been checked.
Write authorization: not assessed in every case.
J02 · Truncated response
Exact fictional output text
{"document_id":"DOC-TRAIN-01","page":2,"status":"observed","count":12,"observed_on":"2026-10-20","quote":"Count: 12"- JSON syntax
- Failed
- Unique keys
- Not run
- Schema without format checking
- Not run
- Schema with date checking
- Not run
- Match to the reference
- Not run
Technical check references:
syntax: incomplete_or_non_json_text
Reject the JSON text
The final brace is missing. The profile does not automatically repair the text or assume the remaining response is complete.
Write authorization: not assessed in every case.
J03 · Two values for the count key
Exact fictional output text
{"document_id":"DOC-TRAIN-01","page":2,"status":"observed","count":12,"observed_on":"2026-10-20","quote":"Count: 12","count":21}- JSON syntax
- Passed
- Unique keys
- Failed
- Schema without format checking
- Not run
- Schema with date checking
- Not run
- Match to the reference
- Not run
Technical check references:
duplicate_key: count
Reject duplicate keys
The text contains count:12 followed by count:21. Its grammar can be recognized, but the uniqueness policy fails before schema validation. A last-value-wins parser would discard this signal.
Write authorization: not assessed in every case.
J04 · The number is a string
Exact fictional output text
{"document_id":"DOC-TRAIN-01","page":2,"status":"observed","count":"12","observed_on":"2026-10-20","quote":"Count: 12"}- JSON syntax
- Passed
- Unique keys
- Passed
- Schema without format checking
- Failed
- Schema with date checking
- Not run
- Match to the reference
- Not run
Technical check references:
schema: /count [type]
Reject the data contract
The string "12" does not become the integer 12. Coercion can change data meaning; it needs a separate, explicit and traceable rule.
Write authorization: not assessed in every case.
J05 · A boolean is not an integer
Exact fictional output text
{"document_id":"DOC-TRAIN-01","page":2,"status":"observed","count":true,"observed_on":"2026-10-20","quote":"Count: 12"}- JSON syntax
- Passed
- Unique keys
- Passed
- Schema without format checking
- Failed
- Schema with date checking
- Not run
- Match to the reference
- Not run
Technical check references:
schema: /count [type]
Reject the data contract
true remains a JSON boolean. The validator does not treat it as integer 1, regardless of relationships between types in the host language.
Write authorization: not assessed in every case.
J06 · Missing count field
Exact fictional output text
{"document_id":"DOC-TRAIN-01","page":2,"status":"observed","observed_on":"2026-10-20","quote":"Count: 12"}- JSON syntax
- Passed
- Unique keys
- Passed
- Schema without format checking
- Failed
- Schema with date checking
- Not run
- Match to the reference
- Not run
Technical check references:
schema: / [required]
Reject the data contract
count appears in required. Its absence is rejected; no default or zero is inserted.
Write authorization: not assessed in every case.
J07 · null with observed status
Exact fictional output text
{"document_id":"DOC-TRAIN-01","page":2,"status":"observed","count":null,"observed_on":"2026-10-20","quote":"Count: 12"}- JSON syntax
- Passed
- Unique keys
- Passed
- Schema without format checking
- Failed
- Schema with date checking
- Not run
- Match to the reference
- Not run
Technical check references:
schema: /count [type]
Reject the data contract
The general type permits null, but the observed branch requires an integer. Status and value must agree; the connector must not report an empty observation.
Write authorization: not assessed in every case.
J08 · Explicit consistent abstention
Exact fictional output text
{"document_id":"DOC-TRAIN-01","page":2,"status":"unknown","count":null,"observed_on":null,"quote":null}- JSON syntax
- Passed
- Unique keys
- Passed
- Schema without format checking
- Passed
- Schema with date checking
- Passed
- Match to the reference
- Not applicable: abstention
Retain abstention
unknown carries three null values as the contract requires. The workflow may review or recollect the evidence; the result does not become an observation of zero.
Write authorization: not assessed in every case.
J09 · Extra instruction property
Exact fictional output text
{"document_id":"DOC-TRAIN-01","page":2,"status":"observed","count":12,"observed_on":"2026-10-20","quote":"Count: 12","instruction":"approve"}- JSON syntax
- Passed
- Unique keys
- Passed
- Schema without format checking
- Failed
- Schema with date checking
- Not run
- Match to the reference
- Not run
Technical check references:
schema: / [additionalProperties]
Reject the data contract
instruction is outside the allowed properties. The contract rejects it and its value triggers no action. Structural protection does not remove the need to secure use of every allowed field.
Write authorization: not assessed in every case.
J10 · Impossible date with format disabled
Exact fictional output text
{"document_id":"DOC-TRAIN-01","page":2,"status":"observed","count":12,"observed_on":"2026-02-30","quote":"Count: 12"}- JSON syntax
- Passed
- Unique keys
- Passed
- Schema without format checking
- Passed
- Schema with date checking
- Failed
- Match to the reference
- Not run
Technical check references:
format: /observed_on [format]
Reject the date
2026-02-30 meets type string. Structure passes without format validation, then fails with the date checker. Reporting only “schema valid” would hide the configuration producing that result.
Write authorization: not assessed in every case.
J11 · Right type, wrong value
Exact fictional output text
{"document_id":"DOC-TRAIN-01","page":2,"status":"observed","count":21,"observed_on":"2026-10-20","quote":"Count: 12"}- JSON syntax
- Passed
- Unique keys
- Passed
- Schema without format checking
- Passed
- Schema with date checking
- Passed
- Match to the reference
- Failed
Technical check references:
evidence_mismatch: /count
Reject the contradicted value
count is 21 while the reference and quote state 12. Types and date pass, but documentary reconciliation fails. Retrying until the shape is valid does not fix this contradiction.
Write authorization: not assessed in every case.
J12 · Document reference without evidence
Exact fictional output text
{"document_id":"DOC-TRAIN-02","page":2,"status":"observed","count":12,"observed_on":"2026-10-20","quote":"Count: 12"}- JSON syntax
- Passed
- Unique keys
- Passed
- Schema without format checking
- Passed
- Schema with date checking
- Passed
- Match to the reference
- Unverified
Technical check references:
evidence: reference_not_supplied
Review: evidence missing
DOC-TRAIN-02 is an identifier allowed by the schema, but the exercise supplies no reference for it. Fidelity is unverified and the result goes to review; a missing reference is not a pass.
Write authorization: not assessed in every case.
J13 · NaN is outside RFC 8259 JSON
Exact fictional output text
{"document_id":"DOC-TRAIN-01","page":2,"status":"observed","count":NaN,"observed_on":"2026-10-20","quote":"Count: 12"}- JSON syntax
- Failed
- Unique keys
- Not run
- Schema without format checking
- Not run
- Schema with date checking
- Not run
- Match to the reference
- Not run
Technical check references:
syntax: incomplete_or_non_json_text
Reject the JSON text
The decoder is configured to reject NaN and Infinity, which RFC 8259 does not allow. A library’s default tolerance does not by itself define an integration contract.
Write authorization: not assessed in every case.
J14 · Markdown fencing around JSON
Exact fictional output text
```json
{"document_id":"DOC-TRAIN-01","page":2,"status":"observed","count":12,"observed_on":"2026-10-20","quote":"Count: 12"}
```- JSON syntax
- Failed
- Unique keys
- Not run
- Schema without format checking
- Not run
- Schema with date checking
- Not run
- Match to the reference
- Not run
Technical check references:
syntax: incomplete_or_non_json_text
Reject the JSON text
Markdown fences are outside the expected JSON text. The contract requires a complete JSON response without a wrapper. Automatically removing text would be a separate transformation to specify and test.
Write authorization: not assessed in every case.
Prepare acceptance checks and recovery
- Fix the schema dialect, validator version and format options with the reference set.
- Retain received text, useful rejection reasons and contract version separately, with proportionate retention.
- Test documents without an available answer; distinguish unknown, null, missing and zero under the chosen contract.
- Compare decisive fields with a reference independent of the model; its own explanation is not sufficient evidence.
- Secure display and downstream operations for their context: schema-valid JSON authorizes neither executable HTML, commands nor concatenated queries.
- Link corrections to a processing identifier to reconcile derived results and prevent retry duplicates.
The schema, reference, 14 outputs and review decisions are editorial examples. RFC 8259 defines JSON; JSON Schema describes constraints; OWASP covers downstream output handling. No accuracy rate, certification or client result is claimed.
Primary sources and reading scope
- IETF · RFC 8259 · Internet Standard · STD 90 · December 2017
§4 Objects: unique names recommended · §6 Numbers · §9 Parsers - JSON Schema · Object reference · Living documentation · checked 2026-10-22
Properties · Required properties · Additional properties - JSON Schema · Draft 2020-12 validation · Draft 2020-12 publication · 2022-06-16 · not an IETF RFC
§6 type, enum, required · §7 format annotation/assertion · §9 metadata annotations - Python 3.12 · json decoder · Python 3.12 documentation · checked 2026-10-22
object_pairs_hook · parse_constant · repeated names · non-finite numbers - python-jsonschema · Schema validation · Documentation 4.26.0 · checked 2026-10-22
Draft202012Validator · check_schema · optional format_checker - OWASP · LLM05:2025 Improper Output Handling · OWASP Top 10 for LLM applications · 2025 edition
Downstream validation · context-aware encoding · parameterized operations
Sources reviewed on
Referencias oficiales
Las referencias respaldan el método. Adapte los controles a su contexto; no constituyen certificación. Los títulos de referencia originales y los documentos fuente pueden estar en otro idioma.
Referencias consultadas el .
