简体   繁体   English

根据 javascript 中的模式验证 json

[英]validate json against schema in javascript

Question:问题:

Is there a plain or native javascript way to validate a JSON script against a JSON schema?是否有一种普通的或本机的 javascript 方法来根据 JSON 模式验证 JSON 脚本?

I have found lots of libraries on Github, but no native/plain solution.我在 Github 上找到了很多库,但没有原生/简单的解决方案。 Does EcmaScript not have a specification for this? EcmaScript 没有这方面的规范吗? and do none of the browsers (or nodejs) have a way to validate JSON natively?并且没有任何浏览器(或 nodejs)可以本地验证 JSON 吗?

Context of Question:问题的背景:

I have a very complex schema that I developed.我开发了一个非常复杂的模式。 It is supposed to work along with a script that requires that the JSON data passed into it to comply with the schema.它应该与一个脚本一起工作,该脚本要求将 JSON 数据传递给它以符合模式。

Simply, no.简单地说,没有。

There was something called JSON Schema , which was an Internet Draft which expired in 2013. Internet Drafts are the first stage to producing an Internet Standard .有一种叫做JSON Schema 的东西,它是一个互联网草案,于 2013 年到期。互联网草案是产生互联网标准的第一阶段。 See more about it at the official site , as it seems to potentially still be actively developed, although it is not (to my knowledge) in widespread use.官方网站上查看更多关于它的信息,因为它似乎仍有可能被积极开发,尽管(据我所知)它没有被广泛使用。

An example of the schema:模式的一个例子:

{
  "$schema": "http://json-schema.org/schema#",
  "title": "Product",
  "type": "object",
  "required": ["id", "name", "price"],
  "properties": {
    "id": {
      "type": "number",
      "description": "Product identifier"
    },
    "name": {
      "type": "string",
      "description": "Name of the product"
    },
    "price": {
      "type": "number",
      "minimum": 0
    },
    "tags": {
      "type": "array",
      "items": {
        "type": "string"
      }
    },
    "stock": {
      "type": "object",
      "properties": {
        "warehouse": {
          "type": "number"
        },
        "retail": {
          "type": "number"
        }
      }
    }
  }
}

will validate this example JSON:将验证此示例 JSON:

{
  "id": 1,
  "name": "Foo",
  "price": 123,
  "tags": [
    "Bar",
    "Eek"
  ],
  "stock": {
    "warehouse": 300,
    "retail": 20
  }
}

EDIT As they all (more or less) do the same thing and have very similar syntaxes, performance should be of the biggest concern.编辑因为它们都(或多或少)做同样的事情并且具有非常相似的语法,所以性能应该是最大的问题。 See here for a comparison of JSON validator's performance - the winner is ajv , which is personally what I use for this reason.请参阅此处以比较 JSON 验证器的性能 - 获胜者是ajv ,这是我个人出于这个原因使用的。

There seems to be at least one pure JS solution now ( https://github.com/tdegrunt/jsonschema ) available via npm ( https://www.npmjs.com/package/jsonschema ).现在似乎至少有一种纯 JS 解决方案( https://github.com/tdegrunt/jsonschema )可通过 npm( https://www.npmjs.com/package/jsonschema )获得。 I am not a contributor, although I appreciate their work.我不是贡献者,尽管我很欣赏他们的工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM