针对javascript中的架构验证json [英] validate json against schema in javascript

查看:127
本文介绍了针对javascript中的架构验证json的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题:

是否有普通的或本机的javascript方法来针对JSON模式验证JSON脚本?

Is there a plain or native javascript way to validate a JSON script against a JSON schema?

我在Github上发现了很多库,但没有本机/普通解决方案. EcmaScript对此没有规范吗?并没有浏览器(或nodejs)具有本地验证JSON的方法吗?

I have found lots of libraries on Github, but no native/plain solution. Does EcmaScript not have a specification for this? and do none of the browsers (or nodejs) have a way to validate JSON natively?

问题背景:

我开发了一个非常复杂的架构. 它应该与一个脚本一起使用,该脚本需要将传入的JSON数据与该模式保持一致.

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模式,它是Internet草案,于2013年到期Internet草案是生成 Internet标准的第一步.在官方网站上查看有关此内容的更多信息,因为它可能仍在积极开发中,尽管它不是(据我所知)被广泛使用.

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. 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.

模式示例:

{
  "$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"
        }
      }
    }
  }
}

将验证此示例JSON:

will validate this example JSON:

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

编辑由于它们(或多或少)都执行相同的操作并且具有非常相似的语法,因此性能应该是最大的问题.有关JSON验证程序性能的比较,请参见此处-获胜者为

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.

这篇关于针对javascript中的架构验证json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆