Ir al contenido principal
Versión: 5.7.x

Comparadores de esquema JSON

[Traducción Beta No Oficial]

Esta página fue traducida por PageTurner AI (beta). No está respaldada oficialmente por el proyecto. ¿Encontraste un error? Reportar problema →

MatcherDescriptionTargets
shouldMatchSchemaValidates that a String or kotlinx.serialization.JsonElement matches a JsonSchema. See description below for details on constructing schemas.Multiplatform

Análisis de esquema

Se puede definir un subconjunto de JSON Schemas mediante el análisis de un esquema textual. Por ejemplo:

val parsedSchema = parseSchema(
"""
{
"$id": "https://example.com/geographical-location.schema.json", // will be ignored
"$schema": "https://json-schema.org/draft/2020-12/schema", // will be ignored
"title": "Longitude and Latitude Values", // will be ignored
"description": "A geographical coordinate.", // will be ignored
"required": [ "latitude", "longitude" ],
"type": "object",
"properties": {
"latitude": {
"type": "number",
"minimum": -90,
"maximum": 90
},
"longitude": {
"type": "number",
"minimum": -180,
"maximum": 180
}
}
}
"""
)

o utilizando el DSL incorporado de Kotest:

val addressSchema = jsonSchema {
obj { // object is reserved, obj was chosen over jsonObject for brevity but could be changed ofc, or jsonObject could be added as alternative.
withProperty("street", required = true) { string() }
withProperty("zipCode", required = true) {
integer {
beEven() and beInRange(10000..99999) // supports constructing a matcher that will be used to test values
}
}
additionalProperties = false // triggers failure if other properties are defined in actual
}
}

val personSchema = jsonSchema {
obj {
withProperty("name", required = true) { string() }
withProperty("address") { addressSchema() } // Schemas can re-use other schemas 🎉
}
}

Construcción del esquema

Array

Los arrays se utilizan para elementos ordenados. En JSON, cada elemento de un array puede ser de un tipo diferente.

Longitud (minItems y maxItems)

La longitud del array puede especificarse mediante las palabras clave minItems y maxItems. El valor de cada palabra clave debe ser un número no negativo, con valores predeterminados de 0 e Int.MAX_VALUE.

val lengthBoundedSchema = jsonSchema {
array(minItems = 0, maxItems = 1) { number() }
}

Unicidad

Un esquema puede garantizar que cada elemento de un array sea único. Simplemente establece la palabra clave uniqueItems en true.

val uniqueArray = jsonSchema {
array(uniqueItems = true) { number() }
}

Validación

Una vez definido un esquema, puedes validar String y kotlinx.serialization.JsonElement con respecto a él:

"{}" shouldMatchSchema personSchema

// fails with:
// $.name => Expected string, but was undefined

""" { "name": "Emil", "age": 34 } """
// Passes, since address isn't required and `additionalProperties` are allowed

Limitaciones

⚠️ Ten en cuenta que Kotest solo admite actualmente un subconjunto de JSON Schema. Actualmente faltan las siguientes funcionalidades:

  • $defs y $refs

  • Esquemas recursivos

  • Interpretación de composición de esquemas

  • string.format

  • array.prefixItems,

  • array.contains,

  • array.items = false

  • array.maxContains

  • array.minContains

  • array.uniqueItems

  • enum