Lua json 模式验证器

Lua json schema validator

我已经找了 4 天多了,但我没能找到对基于 lua 的 json 模式编译器的代码的很多支持。主要是我一直在处理

但是以上任何一个都不能直接使用。

在处理 luarocks 上的问题后,我终于让 ljsonschema 工作了,但是 JSON 语法看起来与正常的 JSON 结构不同 - 例如:等于分号的位置,键名没有双引号等。

ljson架构支持

{ type = 'object', properties = {
foo = { type = 'string' },
bar = { type = 'number' },},}

我要求:

{ "type" : "object",
"properties" : {
"foo" : { "type" : "string" },
"bar" : { "type" : "number" }}}

对于 rjson,安装位置本身存在问题。虽然安装顺利,但在 运行 代码 lua 时永远无法找到 .so 文件。另外,我找不到太多的开发支持。

请帮助指出正确的方向,以防我遗漏了什么。 我有 json 模式和示例 json,我只需要一个 lua 代码来帮助围绕它编写程序。

这是为 Kong CE 编写自定义 JSON 验证插件。

更新: 我希望以下代码与 ljsonschema 一起使用:

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 })

但我收到错误消息:'}' expected (to close '{' at line 5) near ':'

看起来 generate_validator 和 myvalidator 的参数是 lua 表,而不是原始的 json 字符串。您需要首先解析 json:

> jsonschema = require 'jsonschema'
> dkjson = require('dkjson')
> schema = [[
>> { "type" : "object",
>> "properties" : {
>> "foo" : { "type" : "string" },
>> "bar" : { "type" : "number" }}}
>> ]]
> s = dkjson.decode(schema)
> myvalidator = jsonschema.generate_validator(s)
>
> json = '{ "foo": "bar", "bar": 42 }'
> print(myvalidator(json))
false   wrong type: expected object, got string
> print(myvalidator(dkjson.decode(json)))
true

好的,我认为 rapidjason 对您有所帮助: 参考 link 这是一个示例工作代码:

local rapidjson = require('rapidjson')

function readAll(file)
    local f = assert(io.open(file, "rb"))
    local content = f:read("*all")
    f:close()
    return content
end

local jsonContent = readAll("sampleJson.txt")
local sampleSchema = readAll("sampleSchema.txt")

local sd = rapidjson.SchemaDocument(sampleSchema)
local validator = rapidjson.SchemaValidator(sd)

local d = rapidjson.Document(jsonContent)

local ok, message = validator:validate(d)
if ok then
    print("json OK")
else
    print(message)
end