{"id":12917,"date":"2022-03-22T08:54:20","date_gmt":"2022-03-22T15:54:20","guid":{"rendered":"https:\/\/www.couchbase.com\/blog\/?p=12917"},"modified":"2025-06-13T21:25:03","modified_gmt":"2025-06-14T04:25:03","slug":"validate-json-documents-in-python-using-pydantic","status":"publish","type":"post","link":"https:\/\/www.couchbase.com\/blog\/es\/validate-json-documents-in-python-using-pydantic\/","title":{"rendered":"Validar documentos JSON en Python con Pydantic"},"content":{"rendered":"<p><span style=\"font-weight: 400\">Uno de los principales atractivos de <\/span><b>bases de datos de documentos<\/b><span style=\"font-weight: 400\"> es la flexibilidad de la estructura o esquema del documento. En la mayor\u00eda de los casos, la flexibilidad del esquema del documento es beneficiosa. Sin embargo, puede haber algunas situaciones en las que tener alguna estructura en el documento puede ser \u00fatil. Este art\u00edculo muestra c\u00f3mo validar tus documentos JSON contra un esquema especificado usando la popular librer\u00eda Python <\/span><a href=\"https:\/\/pydantic-docs.helpmanual.io\/\"><span style=\"font-weight: 400\">pydantic<\/span><\/a><span style=\"font-weight: 400\">.<\/span><\/p>\n<h4><span style=\"font-weight: 400\">\u00bfCu\u00e1ndo hay que validar los documentos?<\/span><\/h4>\n<p><span style=\"font-weight: 400\">Un error com\u00fan sobre el uso de bases de datos NoSQL es que no se requieren estructuras o esquemas de documentos. En la mayor\u00eda de los casos, las aplicaciones suelen tener algunas restricciones para los datos, aunque no las validen espec\u00edficamente. Por ejemplo, puede haber algunos campos en el documento de los que la aplicaci\u00f3n depende para su funcionalidad. Una aplicaci\u00f3n podr\u00eda simplemente no funcionar correctamente si faltan algunos de estos campos JSON p\u00eddanticos.<\/span><\/p>\n<p><span style=\"font-weight: 400\">Un ejemplo real de este problema podr\u00eda ser una aplicaci\u00f3n que lee datos de otra aplicaci\u00f3n poco fiable que env\u00eda peri\u00f3dicamente datos err\u00f3neos. Ser\u00eda prudente resaltar los documentos que podr\u00edan romper la aplicaci\u00f3n en tales casos. Los desarrolladores pueden hacer esto <\/span><i><span style=\"font-weight: 400\">en la aplicaci\u00f3n <\/span><\/i><span style=\"font-weight: 400\">o <\/span><i><span style=\"font-weight: 400\">a nivel de documento<\/span><\/i><span style=\"font-weight: 400\">.\u00a0<\/span><\/p>\n<p><span style=\"font-weight: 400\">En este enfoque, especificamos un esquema de JSON a pydantic para los documentos con el fin de ayudar a identificar aquellos que no coinciden con las especificaciones de la aplicaci\u00f3n a nivel de documento.<\/span><\/p>\n<h4><span style=\"font-weight: 400\">Generar datos de prueba JSON<\/span><\/h4>\n<p><span style=\"font-weight: 400\">Utilizamos la biblioteca de c\u00f3digo abierto, <\/span><a href=\"https:\/\/faker.readthedocs.io\/en\/master\/#\"><span style=\"font-weight: 400\">Farsante<\/span><\/a><span style=\"font-weight: 400\">para generar algunos perfiles de usuario falsos para este tutorial.<\/span><\/p>\n<p><span style=\"font-weight: 400\">Esta es la estructura de un documento \u00fanico:<\/span><\/p>\n<pre class=\"decode-attributes:false lang:js decode:true\">{\r\n  \"job\": \"Radiographer, diagnostic\",\r\n  \"company\": \"Klein, Dillon and Neal\",\r\n  \"residence\": \"2232 Jackson Forks\\nLake Teresa, CO 46959\",\r\n  \"website\": [\r\n    \"https:\/\/bishop-torres.net\/\"\r\n  ],\r\n  \"username\": \"aabbott\",\r\n  \"name\": \"Madison Mitchell\",\r\n  \"address\": \"1782 Moore Hill Apt. 717\\nWest Stephaniestad, NM 75293\",\r\n  \"mail\": \"amberrodriguez@hotmail.com\",\r\n  \"phone\": {\r\n    \"home\": \"677-197-4239x889\",\r\n    \"mobile\": \"001-594-038-9255x99138\"\r\n  }\r\n}<\/pre>\n<p><span style=\"font-weight: 400\">Para simular los documentos rotos, modifico una peque\u00f1a parte de los perfiles de usuario eliminando algunos de los campos de tel\u00e9fono m\u00f3vil y correo. Nuestro objetivo es identificar estos registros que, en el mundo real, se almacenar\u00edan en una base de datos de documentos como Couchbase.<\/span><\/p>\n<p><span style=\"font-weight: 400\">Cargo los datos pydantic generados a partir de JSON en un bucket de nuestro hosted <\/span><a href=\"https:\/\/www.couchbase.com\/blog\/es\/products\/capella\/\"><span style=\"font-weight: 400\">Couchbase Capella<\/span><\/a><span style=\"font-weight: 400\"> cl\u00faster utilizando el <\/span><i><span style=\"font-weight: 400\">importar <\/span><\/i><span style=\"font-weight: 400\">en la interfaz de usuario de la consola web integrada para nuestras pruebas. Especifico el <\/span><i><span style=\"font-weight: 400\">nombre de usuario <\/span><\/i><span style=\"font-weight: 400\">como clave para identificar un\u00edvocamente cada documento.<\/span><\/p>\n<h4><span style=\"font-weight: 400\">\u00bfC\u00f3mo especificar un esquema para documentos JSON?<\/span><\/h4>\n<p><span style=\"font-weight: 400\">En los datos del perfil de usuario, espero que los documentos se ajusten a la siguiente estructura en mis aplicaciones:<\/span><\/p>\n<ul>\n<li style=\"font-weight: 400\"><span style=\"font-weight: 400\">Campos obligatorios:<\/span>\n<ul>\n<li style=\"font-weight: 400\"><span style=\"font-weight: 400\">nombre de usuario<\/span><\/li>\n<li style=\"font-weight: 400\"><span style=\"font-weight: 400\">nombre<\/span><\/li>\n<li style=\"font-weight: 400\"><span style=\"font-weight: 400\">phone - con elementos JSON para \"home\" y \"mobile\".<\/span><\/li>\n<li style=\"font-weight: 400\"><span style=\"font-weight: 400\">correo<\/span><\/li>\n<li style=\"font-weight: 400\"><span style=\"font-weight: 400\">sitio web - una matriz<\/span><\/li>\n<\/ul>\n<\/li>\n<li style=\"font-weight: 400\"><span style=\"font-weight: 400\">Campos opcionales:<\/span>\n<ul>\n<li style=\"font-weight: 400\"><span style=\"font-weight: 400\">empresa<\/span><\/li>\n<li style=\"font-weight: 400\"><span style=\"font-weight: 400\">residencia<\/span><\/li>\n<li style=\"font-weight: 400\"><span style=\"font-weight: 400\">empleo<\/span><\/li>\n<li style=\"font-weight: 400\"><span style=\"font-weight: 400\">direcci\u00f3n<\/span><\/li>\n<\/ul>\n<\/li>\n<\/ul>\n<p><span style=\"font-weight: 400\">Pydantic es una de las bibliotecas m\u00e1s populares en Python para la validaci\u00f3n de datos. La sintaxis para especificar el esquema es similar a usar <\/span><a href=\"https:\/\/docs.python.org\/3\/library\/typing.html\"><span style=\"font-weight: 400\">sugerencias de tipo para funciones en Python<\/span><\/a><span style=\"font-weight: 400\">. Los desarrolladores pueden especificar el esquema definiendo un modelo. Pydantic tiene un rico conjunto de caracter\u00edsticas para hacer una variedad de validaciones JSON. Vamos a caminar a trav\u00e9s de la representaci\u00f3n de algunas especificaciones de documentos de perfil de usuario.<\/span><\/p>\n<p><span style=\"font-weight: 400\">Una cosa a tener en cuenta sobre pydantic es que, por defecto, intenta coaccionar los tipos de datos haciendo conversiones de tipo cuando es posible - por ejemplo, convertir la cadena '1' en un num\u00e9rico 1. Sin embargo, existe una opci\u00f3n para <\/span><a href=\"https:\/\/pydantic-docs.helpmanual.io\/usage\/types\/#strict-types\"><span style=\"font-weight: 400\">activar la comprobaci\u00f3n estricta de tipos<\/span><\/a><span style=\"font-weight: 400\"> sin realizar conversiones.<\/span><\/p>\n<p><span style=\"font-weight: 400\">En este ejemplo de c\u00f3digo, puedes ver una configuraci\u00f3n b\u00e1sica para el esquema UserProfile utilizando sintaxis pydantic:<\/span><\/p>\n<pre class=\"decode-attributes:false lang:python decode:true\">class UserProfile(BaseModel):\r\n\u00a0\u00a0\u00a0\"\"\"Schema for User Profiles\"\"\"\r\n\u00a0\u00a0\u00a0username: str\r\n\u00a0\u00a0\u00a0name: str\r\n\u00a0\u00a0\u00a0phone: Phone\r\n\u00a0\u00a0\u00a0mail: str\r\n\u00a0\u00a0\u00a0company: Optional[str]\r\n\u00a0\u00a0\u00a0residence: Optional[str]\r\n\u00a0\u00a0\u00a0website: List[HttpUrl]\r\n\u00a0\u00a0\u00a0job: Optional[str]\r\n\u00a0\u00a0\u00a0address: Optional[str]<\/pre>\n<p><span style=\"font-weight: 400\">Cada campo se especifica junto con el tipo de datos previsto. Los campos opcionales se marcan como <\/span><i><span style=\"font-weight: 400\">Opcional<\/span><\/i><span style=\"font-weight: 400\">. Una matriz se especifica mediante el par\u00e1metro <\/span><i><span style=\"font-weight: 400\">Lista <\/span><\/i><span style=\"font-weight: 400\">seguida del tipo de datos deseado.<\/span><\/p>\n<p><span style=\"font-weight: 400\">En <\/span><i><span style=\"font-weight: 400\">nombre de usuario <\/span><\/i><span style=\"font-weight: 400\">debe ser una cadena, mientras que el campo <\/span><i><span style=\"font-weight: 400\">empresa <\/span><\/i><span style=\"font-weight: 400\">es una cadena opcional. Si nos fijamos en las otras l\u00edneas del fragmento de c\u00f3digo, veremos que el campo <\/span><i><span style=\"font-weight: 400\">sitio web <\/span><\/i><span style=\"font-weight: 400\">es una lista de tipo <\/span><i><span style=\"font-weight: 400\">HttpUrl - <\/span><\/i><span style=\"font-weight: 400\">uno de los muchos tipos personalizados proporcionados por pydantic. <\/span><i><span style=\"font-weight: 400\">HttpUrl <\/span><\/i><span style=\"font-weight: 400\">se utiliza para validar que la URL es v\u00e1lida y no cadenas aleatorias. Del mismo modo, hay otros campos como <\/span><i><span style=\"font-weight: 400\">correos electr\u00f3nicos <\/span><\/i><span style=\"font-weight: 400\">que podr\u00edamos utilizar para asegurarnos de que los campos de correo electr\u00f3nico son un formulario v\u00e1lido.\u00a0<\/span><\/p>\n<p><span style=\"font-weight: 400\">Si nos fijamos en el <\/span><i><span style=\"font-weight: 400\">tel\u00e9fono <\/span><\/i><span style=\"font-weight: 400\">se marca como <\/span><i><span style=\"font-weight: 400\">Tel\u00e9fono <\/span><\/i><span style=\"font-weight: 400\">que es un tipo personalizado que definiremos en el siguiente fragmento de c\u00f3digo:<\/span><\/p>\n<pre class=\"decode-attributes:false lang:python decode:true\">class Phone(BaseModel):\r\n   \"\"\"Schema for Phone numbers\"\"\"\r\n   home: str\r\n   mobile: str\r\n\r\n   @validator(\"mobile\", \"home\")\r\n   def does_not_contain_extension(cls, v):\r\n       \"\"\"Check if the phone numbers contain extensions\"\"\"\r\n       if \"x\" in v:\r\n         raise ExtensionError(wrong_value=v)\r\n       return v<\/pre>\n<p><span style=\"font-weight: 400\">Aqu\u00ed especificamos que el <\/span><i><span style=\"font-weight: 400\">Tel\u00e9fono <\/span><\/i><span style=\"font-weight: 400\">se compone de dos campos que son cadenas: <\/span><i><span style=\"font-weight: 400\">Inicio <\/span><\/i><span style=\"font-weight: 400\">y <\/span><i><span style=\"font-weight: 400\">m\u00f3vil<\/span><\/i><span style=\"font-weight: 400\">. Esto se comprobar\u00eda dentro del <\/span><i><span style=\"font-weight: 400\">Perfil de usuario <\/span><\/i><span style=\"font-weight: 400\">modelo e interpretado como el <\/span><i><span style=\"font-weight: 400\">Perfil de usuario <\/span><\/i><span style=\"font-weight: 400\">que contiene un <\/span><i><span style=\"font-weight: 400\">tel\u00e9fono <\/span><\/i><span style=\"font-weight: 400\">que contiene <\/span><i><span style=\"font-weight: 400\">Inicio <\/span><\/i><span style=\"font-weight: 400\">y <\/span><i><span style=\"font-weight: 400\">m\u00f3vil <\/span><\/i><span style=\"font-weight: 400\">campos.\u00a0<\/span><\/p>\n<p><span style=\"font-weight: 400\">Pydantic tambi\u00e9n nos permite validar la <\/span><i><span style=\"font-weight: 400\">contenidos <\/span><\/i><span style=\"font-weight: 400\">de los datos y el tipo y presencia de los mismos. Puede hacerlo definiendo funciones que validen campos espec\u00edficos. En el ejemplo anterior, validamos el campo <\/span><i><span style=\"font-weight: 400\">m\u00f3vil <\/span><\/i><span style=\"font-weight: 400\">y <\/span><i><span style=\"font-weight: 400\">Inicio <\/span><\/i><span style=\"font-weight: 400\">para comprobar si contienen extensiones. Si contienen una extensi\u00f3n, no la soportamos y lanzamos un error personalizado. Estos errores de esquema se muestran a los usuarios que realizan la validaci\u00f3n pydantic.<\/span><\/p>\n<p><span style=\"font-weight: 400\">Puede ver la definici\u00f3n del esquema especificando la opci\u00f3n <\/span><i><span style=\"font-weight: 400\">Modelo.schema_json()<\/span><\/i><span style=\"font-weight: 400\"> como se muestra aqu\u00ed:<\/span><\/p>\n<pre class=\"decode-attributes:false lang:js decode:true\">{\r\n  \"title\": \"UserProfile\",\r\n  \"description\": \"Schema for User Profiles\",\r\n  \"type\": \"object\",\r\n  \"properties\": {\r\n    \"username\": {\r\n      \"title\": \"Username\",\r\n      \"type\": \"string\"\r\n    },\r\n    \"name\": {\r\n      \"title\": \"Name\",\r\n      \"type\": \"string\"\r\n    },\r\n    \"phone\": {\r\n      \"$ref\": \"#\/definitions\/Phone\"\r\n    },\r\n    \"mail\": {\r\n      \"title\": \"Mail\",\r\n      \"type\": \"string\"\r\n    },\r\n    \"company\": {\r\n      \"title\": \"Company\",\r\n      \"type\": \"string\"\r\n    },\r\n    \"residence\": {\r\n      \"title\": \"Residence\",\r\n      \"type\": \"string\"\r\n    },\r\n    \"website\": {\r\n      \"title\": \"Website\",\r\n      \"type\": \"array\",\r\n      \"items\": {\r\n        \"type\": \"string\",\r\n        \"minLength\": 1,\r\n        \"maxLength\": 2083,\r\n        \"format\": \"uri\"\r\n      }\r\n    },\r\n    \"job\": {\r\n      \"title\": \"Job\",\r\n      \"type\": \"string\"\r\n    },\r\n    \"address\": {\r\n      \"title\": \"Address\",\r\n      \"type\": \"string\"\r\n    }\r\n  },\r\n  \"required\": [\r\n    \"username\",\r\n    \"name\",\r\n    \"phone\",\r\n    \"mail\",\r\n    \"website\"\r\n  ],\r\n  \"definitions\": {\r\n    \"Phone\": {\r\n      \"title\": \"Phone\",\r\n      \"description\": \"Schema for Phone numbers\",\r\n      \"type\": \"object\",\r\n      \"properties\": {\r\n        \"home\": {\r\n          \"title\": \"Home\",\r\n          \"type\": \"string\"\r\n        },\r\n        \"mobile\": {\r\n          \"title\": \"Mobile\",\r\n          \"type\": \"string\"\r\n        }\r\n      },\r\n      \"required\": [\r\n        \"home\",\r\n        \"mobile\"\r\n      ]\r\n    }\r\n  }\r\n}\r\n<\/pre>\n<h4><span style=\"color: #343e47;font-family: Lato, 'Helvetica Neue', Helvetica, Arial, sans-serif;font-size: 50px\">Validaci\u00f3n de documentos JSON con respecto a un esquema pydantic de Python<\/span><\/h4>\n<p><span style=\"font-weight: 400\">Ahora que hemos definido el esquema, vamos a explorar c\u00f3mo podemos validar los documentos contra el esquema.<\/span><\/p>\n<p><span style=\"font-weight: 400\">La validaci\u00f3n puede realizarse utilizando la pydantic <\/span><i><span style=\"font-weight: 400\">parse_obj<\/span><\/i><span style=\"font-weight: 400\"> del modelo. Se especifica el documento como un diccionario y se comprueba si hay excepciones de validaci\u00f3n. En este caso, obtenemos todos los documentos (hasta el l\u00edmite especificado) utilizando una consulta Couchbase y los comprobamos uno a uno e informamos de cualquier error.<\/span><\/p>\n<pre class=\"decode-attributes:false lang:python decode:true\">password_authenticator = PasswordAuthenticator(DB_USER, DB_PWD)\r\n    cluster = Cluster(\r\n       CONN_STR,\r\n       ClusterOptions(password_authenticator),\r\n    )\r\n   validation_error_count = 0\r\n   query = f\"select profile.* from `{BUCKET}`.{SCOPE}.{COLLECTION} profile LIMIT {DOCUMENT_LIMIT}\"\r\n   try:\r\n      results = cluster.query(query)\r\n      for row in results:\r\n         try:\r\n            UserProfile.parse_obj(row)\r\n            validation_error_count += 1\r\n         except ValidationError as e:\r\n               print(f\"Error found in document: {row['username']}\\n\", e.json())\r\n   except Exception as e:\r\n       print(e)\r\n\r\n   print(f\"Validation Error Count: {validation_error_count}\")<\/pre>\n<p><span style=\"font-weight: 400\">El esquema destaca algunos de los errores observados en los documentos:<\/span><\/p>\n<pre class=\"decode-attributes:false lang:js decode:true\">Error found in document: aarias\r\n\u00a0[\r\n\u00a0\u00a0{\r\n\u00a0\u00a0\u00a0\u00a0\"loc\": [\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\"phone\",\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\"home\"\r\n\u00a0\u00a0\u00a0\u00a0],\r\n\u00a0\u00a0\u00a0\u00a0\"msg\": \"value is an extension, got \\\"(932)532-4001x319\\\"\",\r\n\u00a0\u00a0\u00a0\u00a0\"type\": \"value_error.extension\",\r\n\u00a0\u00a0\u00a0\u00a0\"ctx\": {\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\"wrong_value\": \"(932)532-4001x319\"\r\n\u00a0\u00a0\u00a0\u00a0}\r\n\u00a0\u00a0},\r\n\u00a0\u00a0{\r\n\u00a0\u00a0\u00a0\u00a0\"loc\": [\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\"phone\",\r\n\u00a0\u00a0\u00a0\u00a0\u00a0\u00a0\"mobile\"\r\n\u00a0\u00a0\u00a0\u00a0],\r\n\u00a0\u00a0\u00a0\u00a0\"msg\": \"field required\",\r\n\u00a0\u00a0\u00a0\u00a0\"type\": \"value_error.missing\"\r\n\u00a0\u00a0}\r\n]<\/pre>\n<p><span style=\"font-weight: 400\">El documento con el ID <\/span><i><span style=\"font-weight: 400\">aarias<\/span><\/i><span style=\"font-weight: 400\"> tiene extensiones en el campo de origen, y el <\/span><i><span style=\"font-weight: 400\">tel\u00e9fono <\/span><\/i><span style=\"font-weight: 400\">\u2192 <\/span><i><span style=\"font-weight: 400\">m\u00f3vil <\/span><\/i><span style=\"font-weight: 400\">tambi\u00e9n falta.<\/span><\/p>\n<h4><span style=\"font-weight: 400\">Resumen<\/span><\/h4>\n<p><span style=\"font-weight: 400\">Este ejemplo de perfil de usuario muestra c\u00f3mo podemos crear f\u00e1cilmente esquemas personalizados para nuestros documentos JSON. Este post tambi\u00e9n muestra c\u00f3mo utilizar las capacidades de prueba y validaci\u00f3n de Python y el m\u00f3dulo pydantic. Es s\u00f3lo la punta del iceberg, aunque hay muchos m\u00e1s <\/span><a href=\"https:\/\/pydantic-docs.helpmanual.io\/usage\/types\/\"><span style=\"font-weight: 400\">tipos<\/span><\/a><span style=\"font-weight: 400\"> que podamos validar.\u00a0<\/span><\/p>\n<p><span style=\"font-weight: 400\">Tambi\u00e9n son posibles otros enfoques; por ejemplo, puedes validar los datos en el momento de escribirlos. Esto se puede hacer muy f\u00e1cilmente integrando el esquema que hemos definido aqu\u00ed con la aplicaci\u00f3n y verificando los datos antes de insertarlos\/upsertarlos en Couchbase.<\/span><\/p>\n<p><span style=\"font-weight: 400\">El c\u00f3digo completo de esta demostraci\u00f3n se encuentra en <\/span><a href=\"https:\/\/github.com\/nithishr\/json-schema-validation\"><span style=\"font-weight: 400\">Github<\/span><\/a><span style=\"font-weight: 400\">. All\u00ed tambi\u00e9n se encuentran las instrucciones para generar los datos y ejecutar los scripts.<\/span><\/p>\n<h4>Recursos<\/h4>\n<ul>\n<li><a href=\"https:\/\/github.com\/nithishr\/json-schema-validation\">Validaci\u00f3n del esquema JSON<\/a> - Repositorio GitHub para el c\u00f3digo de este post<\/li>\n<li><a href=\"https:\/\/www.couchbase.com\/blog\/es\/products\/capella\/\"><span style=\"font-weight: 400\">Couchbase Capella<\/span><\/a> &#8211; <a href=\"https:\/\/www.couchbase.com\/blog\/es\/products\/capella\/\">DBaaS NoSQL totalmente alojada<\/a><\/li>\n<li><a href=\"https:\/\/pydantic-docs.helpmanual.io\/\">M\u00f3dulo pydantic de Python<\/a><\/li>\n<li><a href=\"https:\/\/faker.readthedocs.io\/en\/master\/#\">M\u00f3dulo Python Faker<\/a><\/li>\n<\/ul>","protected":false},"excerpt":{"rendered":"<p>One of the main attractions of document databases is the flexibility of the document structure or schema. For the most part, the flexibility in the document schema is beneficial. However, there might be some situations where having some structure to [&hellip;]<\/p>","protected":false},"author":80878,"featured_media":10763,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"inline_featured_image":false,"footnotes":""},"categories":[1816,1819,9139],"tags":[1261,1488],"ppma_author":[9544],"class_list":["post-12917","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-couchbase-server","category-data-modeling","category-python","tag-json","tag-schema"],"acf":[],"yoast_head":"<!-- This site is optimized with the Yoast SEO Premium plugin v25.8 (Yoast SEO v25.8) - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>JSON Validation Against Pydantic Schema Tutorial | Couchbase<\/title>\n<meta name=\"description\" content=\"Find out how to validate JSON documents against a specified schema using the popular Python library pydantic. Get validation best practices at Couchbase.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/www.couchbase.com\/blog\/es\/validate-json-documents-in-python-using-pydantic\/\" \/>\n<meta property=\"og:locale\" content=\"es_MX\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Validate JSON Documents in Python using Pydantic\" \/>\n<meta property=\"og:description\" content=\"Find out how to validate JSON documents against a specified schema using the popular Python library pydantic. Get validation best practices at Couchbase.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/www.couchbase.com\/blog\/es\/validate-json-documents-in-python-using-pydantic\/\" \/>\n<meta property=\"og:site_name\" content=\"The Couchbase Blog\" \/>\n<meta property=\"article:published_time\" content=\"2022-03-22T15:54:20+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2025-06-14T04:25:03+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/www.couchbase.com\/blog\/wp-content\/uploads\/sites\/1\/2021\/02\/MFA-BGimage-lg.jpg\" \/>\n\t<meta property=\"og:image:width\" content=\"1200\" \/>\n\t<meta property=\"og:image:height\" content=\"800\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/jpeg\" \/>\n<meta name=\"author\" content=\"Nithish Raghunandanan\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Nithish Raghunandanan\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"5 minutos\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\/\/www.couchbase.com\/blog\/validate-json-documents-in-python-using-pydantic\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/www.couchbase.com\/blog\/validate-json-documents-in-python-using-pydantic\/\"},\"author\":{\"name\":\"nithishr\",\"@id\":\"https:\/\/www.couchbase.com\/blog\/#\/schema\/person\/c5a843d75ad78b5b698f59ca6d123af2\"},\"headline\":\"Validate JSON Documents in Python using Pydantic\",\"datePublished\":\"2022-03-22T15:54:20+00:00\",\"dateModified\":\"2025-06-14T04:25:03+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/www.couchbase.com\/blog\/validate-json-documents-in-python-using-pydantic\/\"},\"wordCount\":1046,\"commentCount\":0,\"publisher\":{\"@id\":\"https:\/\/www.couchbase.com\/blog\/#organization\"},\"image\":{\"@id\":\"https:\/\/www.couchbase.com\/blog\/validate-json-documents-in-python-using-pydantic\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/www.couchbase.com\/blog\/wp-content\/uploads\/sites\/1\/2021\/02\/MFA-BGimage-lg.jpg\",\"keywords\":[\"JSON\",\"Schema\"],\"articleSection\":[\"Couchbase Server\",\"Data Modeling\",\"Python\"],\"inLanguage\":\"es\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\/\/www.couchbase.com\/blog\/validate-json-documents-in-python-using-pydantic\/#respond\"]}]},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/www.couchbase.com\/blog\/validate-json-documents-in-python-using-pydantic\/\",\"url\":\"https:\/\/www.couchbase.com\/blog\/validate-json-documents-in-python-using-pydantic\/\",\"name\":\"JSON Validation Against Pydantic Schema Tutorial | Couchbase\",\"isPartOf\":{\"@id\":\"https:\/\/www.couchbase.com\/blog\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\/\/www.couchbase.com\/blog\/validate-json-documents-in-python-using-pydantic\/#primaryimage\"},\"image\":{\"@id\":\"https:\/\/www.couchbase.com\/blog\/validate-json-documents-in-python-using-pydantic\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/www.couchbase.com\/blog\/wp-content\/uploads\/sites\/1\/2021\/02\/MFA-BGimage-lg.jpg\",\"datePublished\":\"2022-03-22T15:54:20+00:00\",\"dateModified\":\"2025-06-14T04:25:03+00:00\",\"description\":\"Find out how to validate JSON documents against a specified schema using the popular Python library pydantic. Get validation best practices at Couchbase.\",\"breadcrumb\":{\"@id\":\"https:\/\/www.couchbase.com\/blog\/validate-json-documents-in-python-using-pydantic\/#breadcrumb\"},\"inLanguage\":\"es\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/www.couchbase.com\/blog\/validate-json-documents-in-python-using-pydantic\/\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"es\",\"@id\":\"https:\/\/www.couchbase.com\/blog\/validate-json-documents-in-python-using-pydantic\/#primaryimage\",\"url\":\"https:\/\/www.couchbase.com\/blog\/wp-content\/uploads\/sites\/1\/2021\/02\/MFA-BGimage-lg.jpg\",\"contentUrl\":\"https:\/\/www.couchbase.com\/blog\/wp-content\/uploads\/sites\/1\/2021\/02\/MFA-BGimage-lg.jpg\",\"width\":1200,\"height\":800,\"caption\":\"\\\"binary damage code\\\" by Markus Spiske, Public Domain Image\"},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/www.couchbase.com\/blog\/validate-json-documents-in-python-using-pydantic\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/www.couchbase.com\/blog\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Validate JSON Documents in Python using Pydantic\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/www.couchbase.com\/blog\/#website\",\"url\":\"https:\/\/www.couchbase.com\/blog\/\",\"name\":\"The Couchbase Blog\",\"description\":\"Couchbase, the NoSQL Database\",\"publisher\":{\"@id\":\"https:\/\/www.couchbase.com\/blog\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/www.couchbase.com\/blog\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"es\"},{\"@type\":\"Organization\",\"@id\":\"https:\/\/www.couchbase.com\/blog\/#organization\",\"name\":\"The Couchbase Blog\",\"url\":\"https:\/\/www.couchbase.com\/blog\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"es\",\"@id\":\"https:\/\/www.couchbase.com\/blog\/#\/schema\/logo\/image\/\",\"url\":\"https:\/\/www.couchbase.com\/blog\/wp-content\/uploads\/2023\/04\/admin-logo.png\",\"contentUrl\":\"https:\/\/www.couchbase.com\/blog\/wp-content\/uploads\/2023\/04\/admin-logo.png\",\"width\":218,\"height\":34,\"caption\":\"The Couchbase Blog\"},\"image\":{\"@id\":\"https:\/\/www.couchbase.com\/blog\/#\/schema\/logo\/image\/\"}},{\"@type\":\"Person\",\"@id\":\"https:\/\/www.couchbase.com\/blog\/#\/schema\/person\/c5a843d75ad78b5b698f59ca6d123af2\",\"name\":\"nithishr\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"es\",\"@id\":\"https:\/\/www.couchbase.com\/blog\/#\/schema\/person\/image\/63270a592008f9080fe48b7652fe559f\",\"url\":\"https:\/\/www.couchbase.com\/blog\/wp-content\/uploads\/sites\/1\/2022\/03\/image-4.png\",\"contentUrl\":\"https:\/\/www.couchbase.com\/blog\/wp-content\/uploads\/sites\/1\/2022\/03\/image-4.png\",\"caption\":\"nithishr\"},\"description\":\"Nithish is an engineer who loves to build products that solve real-world problems in short spans of time. He has experienced different areas of the industry having worked in diverse companies in Germany and India. Apart from work, he likes to travel and interact and engage with the tech community through Meetups &amp; Hackathons. In his free time, he likes to try stuff out by hacking things together.\",\"url\":\"https:\/\/www.couchbase.com\/blog\/es\/author\/nithishr\/\"}]}<\/script>\n<!-- \/ Yoast SEO Premium plugin. -->","yoast_head_json":{"title":"JSON Validation Against Pydantic Schema Tutorial | Couchbase","description":"Find out how to validate JSON documents against a specified schema using the popular Python library pydantic. Get validation best practices at Couchbase.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/www.couchbase.com\/blog\/es\/validate-json-documents-in-python-using-pydantic\/","og_locale":"es_MX","og_type":"article","og_title":"Validate JSON Documents in Python using Pydantic","og_description":"Find out how to validate JSON documents against a specified schema using the popular Python library pydantic. Get validation best practices at Couchbase.","og_url":"https:\/\/www.couchbase.com\/blog\/es\/validate-json-documents-in-python-using-pydantic\/","og_site_name":"The Couchbase Blog","article_published_time":"2022-03-22T15:54:20+00:00","article_modified_time":"2025-06-14T04:25:03+00:00","og_image":[{"width":1200,"height":800,"url":"https:\/\/www.couchbase.com\/blog\/wp-content\/uploads\/sites\/1\/2021\/02\/MFA-BGimage-lg.jpg","type":"image\/jpeg"}],"author":"Nithish Raghunandanan","twitter_card":"summary_large_image","twitter_misc":{"Written by":"Nithish Raghunandanan","Est. reading time":"5 minutos"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/www.couchbase.com\/blog\/validate-json-documents-in-python-using-pydantic\/#article","isPartOf":{"@id":"https:\/\/www.couchbase.com\/blog\/validate-json-documents-in-python-using-pydantic\/"},"author":{"name":"nithishr","@id":"https:\/\/www.couchbase.com\/blog\/#\/schema\/person\/c5a843d75ad78b5b698f59ca6d123af2"},"headline":"Validate JSON Documents in Python using Pydantic","datePublished":"2022-03-22T15:54:20+00:00","dateModified":"2025-06-14T04:25:03+00:00","mainEntityOfPage":{"@id":"https:\/\/www.couchbase.com\/blog\/validate-json-documents-in-python-using-pydantic\/"},"wordCount":1046,"commentCount":0,"publisher":{"@id":"https:\/\/www.couchbase.com\/blog\/#organization"},"image":{"@id":"https:\/\/www.couchbase.com\/blog\/validate-json-documents-in-python-using-pydantic\/#primaryimage"},"thumbnailUrl":"https:\/\/www.couchbase.com\/blog\/wp-content\/uploads\/sites\/1\/2021\/02\/MFA-BGimage-lg.jpg","keywords":["JSON","Schema"],"articleSection":["Couchbase Server","Data Modeling","Python"],"inLanguage":"es","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/www.couchbase.com\/blog\/validate-json-documents-in-python-using-pydantic\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/www.couchbase.com\/blog\/validate-json-documents-in-python-using-pydantic\/","url":"https:\/\/www.couchbase.com\/blog\/validate-json-documents-in-python-using-pydantic\/","name":"JSON Validation Against Pydantic Schema Tutorial | Couchbase","isPartOf":{"@id":"https:\/\/www.couchbase.com\/blog\/#website"},"primaryImageOfPage":{"@id":"https:\/\/www.couchbase.com\/blog\/validate-json-documents-in-python-using-pydantic\/#primaryimage"},"image":{"@id":"https:\/\/www.couchbase.com\/blog\/validate-json-documents-in-python-using-pydantic\/#primaryimage"},"thumbnailUrl":"https:\/\/www.couchbase.com\/blog\/wp-content\/uploads\/sites\/1\/2021\/02\/MFA-BGimage-lg.jpg","datePublished":"2022-03-22T15:54:20+00:00","dateModified":"2025-06-14T04:25:03+00:00","description":"Find out how to validate JSON documents against a specified schema using the popular Python library pydantic. Get validation best practices at Couchbase.","breadcrumb":{"@id":"https:\/\/www.couchbase.com\/blog\/validate-json-documents-in-python-using-pydantic\/#breadcrumb"},"inLanguage":"es","potentialAction":[{"@type":"ReadAction","target":["https:\/\/www.couchbase.com\/blog\/validate-json-documents-in-python-using-pydantic\/"]}]},{"@type":"ImageObject","inLanguage":"es","@id":"https:\/\/www.couchbase.com\/blog\/validate-json-documents-in-python-using-pydantic\/#primaryimage","url":"https:\/\/www.couchbase.com\/blog\/wp-content\/uploads\/sites\/1\/2021\/02\/MFA-BGimage-lg.jpg","contentUrl":"https:\/\/www.couchbase.com\/blog\/wp-content\/uploads\/sites\/1\/2021\/02\/MFA-BGimage-lg.jpg","width":1200,"height":800,"caption":"\"binary damage code\" by Markus Spiske, Public Domain Image"},{"@type":"BreadcrumbList","@id":"https:\/\/www.couchbase.com\/blog\/validate-json-documents-in-python-using-pydantic\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/www.couchbase.com\/blog\/"},{"@type":"ListItem","position":2,"name":"Validate JSON Documents in Python using Pydantic"}]},{"@type":"WebSite","@id":"https:\/\/www.couchbase.com\/blog\/#website","url":"https:\/\/www.couchbase.com\/blog\/","name":"El blog de Couchbase","description":"Couchbase, la base de datos NoSQL","publisher":{"@id":"https:\/\/www.couchbase.com\/blog\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/www.couchbase.com\/blog\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"es"},{"@type":"Organization","@id":"https:\/\/www.couchbase.com\/blog\/#organization","name":"El blog de Couchbase","url":"https:\/\/www.couchbase.com\/blog\/","logo":{"@type":"ImageObject","inLanguage":"es","@id":"https:\/\/www.couchbase.com\/blog\/#\/schema\/logo\/image\/","url":"https:\/\/www.couchbase.com\/blog\/wp-content\/uploads\/2023\/04\/admin-logo.png","contentUrl":"https:\/\/www.couchbase.com\/blog\/wp-content\/uploads\/2023\/04\/admin-logo.png","width":218,"height":34,"caption":"The Couchbase Blog"},"image":{"@id":"https:\/\/www.couchbase.com\/blog\/#\/schema\/logo\/image\/"}},{"@type":"Person","@id":"https:\/\/www.couchbase.com\/blog\/#\/schema\/person\/c5a843d75ad78b5b698f59ca6d123af2","name":"nithishr","image":{"@type":"ImageObject","inLanguage":"es","@id":"https:\/\/www.couchbase.com\/blog\/#\/schema\/person\/image\/63270a592008f9080fe48b7652fe559f","url":"https:\/\/www.couchbase.com\/blog\/wp-content\/uploads\/sites\/1\/2022\/03\/image-4.png","contentUrl":"https:\/\/www.couchbase.com\/blog\/wp-content\/uploads\/sites\/1\/2022\/03\/image-4.png","caption":"nithishr"},"description":"Nithish es un ingeniero al que le encanta crear productos que resuelvan problemas del mundo real en poco tiempo. Ha trabajado en diferentes \u00e1reas de la industria en diversas empresas de Alemania y la India. Aparte del trabajo, le gusta viajar e interactuar con la comunidad tecnol\u00f3gica a trav\u00e9s de Meetups y Hackathons. En su tiempo libre, le gusta probar cosas hacke\u00e1ndolas.","url":"https:\/\/www.couchbase.com\/blog\/es\/author\/nithishr\/"}]}},"authors":[{"term_id":9544,"user_id":80878,"is_guest":0,"slug":"nithishr","display_name":"Nithish Raghunandanan","avatar_url":{"url":"https:\/\/www.couchbase.com\/blog\/wp-content\/uploads\/sites\/1\/2022\/03\/image-4.png","url2x":"https:\/\/www.couchbase.com\/blog\/wp-content\/uploads\/sites\/1\/2022\/03\/image-4.png"},"author_category":"","last_name":"Raghunandanan","first_name":"Nithish","job_title":"","user_url":"","description":"Nithish es un ingeniero al que le encanta crear productos que resuelvan problemas del mundo real en poco tiempo. Ha trabajado en diferentes \u00e1reas de la industria en diversas empresas de Alemania y la India. Aparte del trabajo, le gusta viajar e interactuar con la comunidad tecnol\u00f3gica a trav\u00e9s de Meetups y Hackathons. En su tiempo libre, le gusta probar cosas hacke\u00e1ndolas."}],"_links":{"self":[{"href":"https:\/\/www.couchbase.com\/blog\/es\/wp-json\/wp\/v2\/posts\/12917","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.couchbase.com\/blog\/es\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.couchbase.com\/blog\/es\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.couchbase.com\/blog\/es\/wp-json\/wp\/v2\/users\/80878"}],"replies":[{"embeddable":true,"href":"https:\/\/www.couchbase.com\/blog\/es\/wp-json\/wp\/v2\/comments?post=12917"}],"version-history":[{"count":0,"href":"https:\/\/www.couchbase.com\/blog\/es\/wp-json\/wp\/v2\/posts\/12917\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.couchbase.com\/blog\/es\/wp-json\/wp\/v2\/media\/10763"}],"wp:attachment":[{"href":"https:\/\/www.couchbase.com\/blog\/es\/wp-json\/wp\/v2\/media?parent=12917"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.couchbase.com\/blog\/es\/wp-json\/wp\/v2\/categories?post=12917"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.couchbase.com\/blog\/es\/wp-json\/wp\/v2\/tags?post=12917"},{"taxonomy":"author","embeddable":true,"href":"https:\/\/www.couchbase.com\/blog\/es\/wp-json\/wp\/v2\/ppma_author?post=12917"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}