首页 > 解决方案 > Lua json 模式验证器

问题描述

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

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

luarocks在处理ljsonschema.

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

标签: jsonvalidationluaschemakong-plugin

解决方案


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

推荐阅读