json - Lua json 模式验证器
问题描述
我一直在寻找超过 4 天,但我还没有找到对基于 lua 的 json 模式编译器的代码的很多支持。主要是我一直在处理
- ljsonschema ( https://github.com/jdesgats/ljsonschema )
- rjson ( https://luarocks.org/modules/romaboy/rjson )
但是以上任何一个都没有直接使用。
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 ':'
解决方案
看起来 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
推荐阅读
- c# - 我如何知道 .NET Standard 需要哪些平台扩展?
- php - 如何插入多个查询?
- android - 我应该为 consts 创建一个新文件吗?
- c# - 如何使用 C# 控制台应用程序、dotnetzip 库解压缩文件
- python-3.x - 如何在 python 3.0 中修复这种类型的错误?每当我使用传递参数(dict {})时,它都会显示这种类型的错误“NameError:名称'P'未定义”
- sql-server - 在应用程序运行期间识别受影响的表 - SQL Server 2012
- flutter - 无限像素溢出的颤动底部
- gitea - Gitea Docker windows - 致命:身份验证失败
- python - 如何在 Python 中获得近似的浮点值?
- c# - Adding data to db that comes from DTOs