Saltar al contenido principal
Versión: Siguiente

JSON Validate

Historia
LanzamientoModificaciones
21 R2Support of JSON Schema draft 2020-12

JSON Validate ( vJson : Object ; vSchema : Object ) : Object

ParámetrosTipoDescripción
vJsonObjectObjeto JSON a validar
vSchemaObjectJSON schema used to validate JSON objects
ResultadoObjectValidation status and errors (if any)

Descripción

The JSON Validate command checks the compliance of the vJson JSON contents with the rules defined in the vSchema JSON schema. If the JSON is invalid, the command returns a detailed description of error(s).

In vJson, pass a JSON object containing the JSON contents to be validated.

Note: Validating a JSON string consists of checking that it follows the rules defined in a JSON schema. Esto es diferente de la comprobación de que el JSON está bien formado, que se realiza mediante el comando JSON Parse.

In vSchema, pass the JSON schema to use for the validation. For more information on how to create a JSON schema, you may consult the json-schema.org web site.

Supported JSON schema validation drafts

To validate a JSON object, 4D uses the norm described in a JSON Schema Validation draft document. Several versions of these documents have been produced over time.

4D supports two versions of the draft:

  • versión 2020-12 (recomendado). Se soportan todas las partes de la norma, excepto:
    • vocabulary
    • contentEncoding, contentMediaType, and contentSchema (validation of non-JSON content)
    • for references: $dynamicRef/$dynamicAnchor and references in https:...
  • versión 4 (implementación heredada, utilizada por defecto). Note that the support of this norm has more limitations than version 2020-12.

Specifying the version to use

The version to use should be inserted in the schema using the $schema key:

  • versión 2020-12:
"$schema": "https://json-schema.org/draft/2020-12/schema",
  • version 4:
"$schema": "http://json-schema.org/draft-04/schema#",

For compatibility reasons, the version 4 is used if the $schema key is omitted. However, it is recommended to use the version 2020-12 which provides the most reliable controls.

nota

If you declare another schema version using the $schema key, an error is returned.

Validation result

If the JSON schema is not valid, 4D returns a Null object and throws an error that can be caught by an on error call method.

The JSON Validate returns an object that provides the status of the validation. Este objeto puede contener las siguientes propiedades:

Nombre de propiedadTipoDescription
successBooleanTrue si vJson está validado, false en caso contrario. If false, the errors property is also returned
errorsObject collectionList of error objects if the vJson is not validated (see below)

Cada objeto de error de la colección errors contiene las siguientes propiedades:

Nombre de propiedadTipoDescription
codeNumberCódigo de error
jsonPathTextJSON path that cannot be validated in vJson
lineNumberLine number of the error in the JSON file. This property is filled if the JSON has been parsed by JSON Parse with the * parameter. Otherwise, the property is omitted.
messageTextMensaje de error
offsetNumberLine offset of the error in the JSON file. This property is filled if the JSON has been parsed by JSON Parse with the * parameter. Otherwise, the property is omitted.
schemaPathsTextJSON path in the schema that causes the validation error

Error list

Details
Se pueden producir los siguientes errores:
Code**Palabra clave JSONMessage
2multipleOfError while validating against 'multipleOf' key.
3maximumEl valor proporcionado no debe ser superior al especificado en el esquema ("{s1}").
4exclusiveMaximumThe value provided should be less than specified in the schema ("{s1}").
5mínimoThe value provided should not be less than specified in the schema ("{s1}").
6exclusiveMinimumThe value provided should be greater than specified in the schema ("{s1}").
7maxLengthThe string is longer than specified in the schema.
8minLengthThe string is shorter than specified in the schema.
9modeloThe string "{s1}" does not match the pattern in the schema:{s2}.
10additionalItemsError while validating an array. JSON contains more elements than specified in the schema.
11maxItemsThe array contains more items than specified in the schema.
12minItemsThe array contains less items than specified in the schema.
13uniqueItemsError while validating an array. Los elementos no son únicos. Another instance of "{s1}" is already in the array.
14maxPropertiesThe number of properties is greater than specified in the schema.
15minPropertiesThe number of properties is less than specified in the schema.
16requeridoFalta la propiedad requerida "{s1}".
17additionalPropertiesNo hay propiedades adicionales permitidas por el esquema. The property(ies) {s1} should be removed.
18dependenciasThe property "{s1}" requires the property "{s2}".
19enumError while validating against 'enum' key. "{s1}" does not match any enum element in the schema.
20typeTipo incorrecto. El tipo esperado es: {s1}
21oneOfEl JSON coincide con más de un valor.
22oneOfEl JSON no coincide con ningún valor.
23notEl JSON no es válido para el valor 'not'.
24formatThe string does not match ("{s1}")
25constValue "{s1}" does not match the 'const' value in the schema.
26unevalutedPropertiesUnevaluated properties are not allowed by the schema. The property(ies) {s1} should be removed.
27unevalutedItemsUnevaluated array items are not allowed. Item at index {s1} is not covered by any schema.
28propertyNamesProperty name "{s1}" does not validate against the 'propertyNames' schema.
29contieneEl array no contiene ningún elemento que coincida con el esquema 'contains'.
30contieneArray must contain at least {s1} items matching the 'contains' schema, but only {s2} were found.
31contieneEl array debe contener como máximo {s1} elementos que coincidan con el esquema 'contains', pero se ha encontrado {s2}.
32requeridoThe property "{s1}" requires the property "{s2}" to be present.
35prefixItemsArray items at the beginning do not match the 'prefixItems' schemas.
36dependentSchemasValidation failed against 'dependentSchemas'.
37$refReference could not be resolved.
38$refCircular reference detected.

Ejemplo

You want to validate a JSON object with a schema and get the list of validation errors, if any, and store error lines and messages in a text variable:

 var $oResult : Object
 $oResult:=JSON Validate(JSON Parse(myJson;*);mySchema)
 If($oResult.success) //validation successful
    ...
 Else //validation failed
    var $vLNbErr : Integer
    var $vTerrLine : Text
    $vLNbErr:=$oResult.errors.length ///get the number of error(s)
    ALERT(String($vLNbErr)+" validation error(s) found.")
    For($i;0;$vLNbErr)
       $vTerrLine:=$vTerrLine+$oResult.errors[$i].message+" "+String($oResult.errors[$i].line)+Carriage return
    End for
 End if

Ver también

JSON Parse

Propiedades

Número de comando1456
Hilo seguro