【问题标题】:Lua json schema validatorLua json 模式验证器
【发布时间】:2019-10-17 12:06:46
【问题描述】:

我一直在寻找超过 4 天,但我还没有找到对基于 lua 的 json 模式编译器的代码的很多支持。主要是我一直在处理

但是以上任何一个都没有直接使用。

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

ljsonschema 支持

{ 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 ':'

【问题讨论】:

  • 你有尝试使用ljsonschema的例子吗?
  • @Nifim:请参阅更新部分。我已经添加了我正在尝试工作的示例代码。感谢您检查..

标签: json validation lua schema kong-plugin


【解决方案1】:

看起来 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

【讨论】:

  • 感谢@glenn jackman,收到此错误,我错过了什么:lua: /usr/local/share/lua/5.1/jsonschema/init.lua:161: bad argument #1 to 'load '(函数预期,得到字符串)堆栈回溯:[C]:在函数“加载”/usr/local/share/lua/5.1/jsonschema/init.lua:161:在函数中/local/share/lua /5.1/jsonschema/init.lua:160>(尾调用):?在 myvalidator = jsonschema.generate_validator(s)
  • 对不起,不知道。我用 Lua 5.3 测试过
  • 好的,没问题 - 我也将使用 5.3 进行测试。再次感谢您的检查
  • 想出了避免5.1错误的解决方案:使用luajit编译器而不是lua
【解决方案2】:

好的,我认为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

【讨论】:

    猜你喜欢
    • 2016-08-27
    • 2016-05-29
    • 1970-01-01
    • 2011-06-08
    • 2020-12-22
    • 1970-01-01
    • 2020-11-06
    • 1970-01-01
    相关资源
    最近更新 更多