jsonschema

JSON Schema 验证器

$ opm get bsiara/jsonschema

jsonschema: JSON Schema 验证器

此库为 Lua/LuaJIT 提供了一个 JSON Schema 草案 4、草案 6、草案 7 的验证器。请注意,即使它使用了 JSON Schema 语义,它也不受限于 JSON。它也可以用于验证更合理的键值数据格式(Lua 表格、msgpack、bencode 等)。

它被设计用于验证 HTTP API 的传入数据,因此速度相当快:它通过动态地将给定的 Schema 转换为纯 Lua 函数来工作。目前正在进行工作以使其尽可能地对 JIT 友好。

此项目基于 ljsonschema。非常感谢作者 jdesgats 的完美工作。重新实现的原因是我们需要支持 OpenResty 环境,并且我们可以使用仅在 OpenResty 中可用的更多优化方法,这可以使其在 OpenResty 环境中运行得更快。

安装

此模块是纯 Lua/LuaJIT 项目,它支持 Lua 5.2、Lua 5.3、LuaJIT 2.1 beta。

安装此库的首选方法是使用 Luarocks

    luarocks install jsonschema

运行测试

    git submodule update --init --recursive
    make dev
    make test

该项目引用了 pcre 正则表达式库。

如果您使用的是 OpenResty 的 LuaJIT,它将自动使用内置的 ngx.re.find。但是,如果您使用的是 Lua 5.2、5.3 或 LuaJIT 2.1 beta,它将改为使用 lrexlib-pcre

此外,该项目还依赖于 net_url 库,您无论如何都需要安装它。

用法

入门

    local jsonschema = require 'jsonschema'
    
    -- Note: do cache the result of schema compilation as this is a quite
    -- expensive process
    local myvalidator = jsonschema.generate_validator {
      type = 'object',
      properties = {
        foo = { type = 'string' },
        bar = { type = 'number' },
      },
    }
    
    print(myvalidator{ foo='hello', bar=42 })

高级用法

JSON Schema 的一些高级功能无法使用标准库实现,需要使用第三方库才能工作。

为了不强制使用某个特定的库,并且不使这个库对于简单的 Schema 变得臃肿,提供了扩展点:generate_validator 接受第二个表参数,可用于自定义生成的解析器。

    local v = jsonschema.generate_validator(schema, {
        -- a value used to check null elements in the validated documents
        -- defaults to `cjson.null` (if available) or `nil`
        null = null_token,
    
        -- function called to match patterns, defaults to `ngx.re.find` in OpenResty
        -- or `rex.find` from lrexlib-pcre on other occassions.
        -- The pattern given here will obey the ECMA-262 specification.
        match_pattern = function(string, patt)
            return ... -- boolean value
        end,
    
        -- function called to resolve external schemas. It is called with the full
        -- url to fetch (without the fragment part) and must return the
        -- corresponding schema as a Lua table.
        -- There is no default implementation: this function must be provided if
        -- resolving external schemas is required.
        external_resolver = function(url)
            return ... -- Lua table
        end,
    
        -- name when generating the validator function, it might ease debugging as
        -- as it will appear in stack traces.
        name = "myschema",
    })

与 JSONSchema 的差异

由于 Lua 语言的特性,很难实现完全的 JSON Schema 支持。一些限制可以通过前面详细介绍的高级选项解决,但有些功能目前(正确地)不支持。

  • 从 Lua 的角度来看,空表和空数组是相同的。

另一方面,支持一些额外的功能。

  • 类型 table 可用于匹配数组或对象,它也比 arrayobject 快得多,因为它不涉及遍历表以确定它是序列还是哈希。

  • 类型 function 可用于检查函数。

作者

api7

许可证

apache2

依赖项

bsiara/neturl >= 1.1.0

版本