Giter Site home page Giter Site logo

ljsonschema's Introduction

lsjonschema: JSON schema validator

This library provides a JSON schema draft 4 validator for Lua. Note that even though it uses the JSON Schema semantics, it is neither bound or limited to JSON. It can be used to validate saner key/value data formats as well (Lua tables, msgpack, bencode, ...).

It has been designed to validate incoming data for HTTP APIs so it is decently fast: it works by transforming the given schema into a pure Lua function on-the-fly. Work is currently in progress to make it as JIT-friendly as possible.

Installation

This module is pure Lua and does not depend on any particular JSON library (cjson.null will be used for null tokens, but you can override that if necessary, see Advanced usage)

The preferred way to install this library is to use Luarocks:

luarocks install ljsonschema

Running the tests also requires the cjson library and the Telescope test runner:

git submodule update --init --recrusive
luarocks install net-url
luarocks install lua-cjson
luarocks install https://raw.githubusercontent.com/jdesgats/telescope/master/rockspecs/telescope-scm-1.rockspec
tsc ./spec/suite.lua

Usage

Getting started

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

Advanced usage

Some advanced features of JSON Schema are not possible to implement using the standard library and require third party libraries to be work.

In order to not force one particular library, and not bloat this library for the simple schemas, extension points are provided: the generate_validator takes a second table argument that can be used to customise the generated parser.

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 string.find.
    -- The JSON schema specification mentions that the validator should obey
    -- the ECMA-262 specification but Lua pattern matching library is much more
    -- primitive than that. Users might want to use PCRE or other more powerful
    -- libraries here
    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",
})

Differences with JSONSchema

Due to the nature of the Lua language, the full JSON schema support is difficult to reach. Some of the limitations can be solved using the advanced options detailed previously, but some features are not supported (correctly) at this time:

  • Empty tables and empty arrays are the same from Lua point of view
  • Unicode strings are considered as a stream of bytes (so length checks might not behave as expected)

On the other hand, some extra features are supported:

  • The type table can be used to match arrays or objects, it is also much faster than array or object as it does not involve walking the table to find out if it's a sequence or a hash
  • The type function can be used to check for functions

ljsonschema's People

Contributors

jdesgats avatar tieske avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

ljsonschema's Issues

how to cache the generated validator ?

adding this as an issue because I could not find another way to reach out.

-- Note: do cache the result of schema compilation as this is a quite
-- expensive process

I read the above in the examples given, but I am not able to figure out what to cache exactly. can you please share an example of caching the compiled schema

Version between github and luarocks are different

I installed this library and run the example code in readme, but get faild.

lua: /usr/local/share/lua/5.1/jsonschema/init.lua:161: bad argument #1 to 'load' (function expected, got string)                                                                                                  
stack traceback:
        [C]: in function 'load'
        /usr/local/share/lua/5.1/jsonschema/init.lua:161: in function </usr/local/share/lua/5.1/jsonschema/init.lua:160>                                                                                          
        (tail call): ?
        a.lua:5: in main chunk
        [C]: ?

I also find some differences between the actual code I installed and github.
For example, local coro_yield = coroutine.yield is not on luarocks version.
But it's in github source code.

Incompatable with OpenResty

Running example in LUA 5.1 is good.
But when i'm trying to run example in OpenResty (with LuaJIT), it rises an error:

ERROR: attempt to yield across C-call boundary
stack traceback:
coroutine.wrap:21: in function coroutine.wrap:21
[C]: in function 'load'
./jsonschema/init.lua:169: in function 'generate_validator'
test.lua:5: in function 'file_gen'
init_worker_by_lua:45: in function <init_worker_by_lua:43>
[C]: in function 'xpcall'
init_worker_by_lua:52: in function <init_worker_by_lua:50>

Full list of Error messages

In case there are more than 2 errors in the document, how can we get the complete list? The ljsonschema currently returns only 1 error.

string pattern

I got this error message

property "private_token" validation failed: failed to match pattern "[a-fA-F0-9]{32}" with "6DA43D15DA6DC5BFD9D347EBAAAB72A9"

But I test on https://regex101.com/ actually it's passed.
Is this a bug? or I'm using the wrong way?

String pattern not work

Hi, ljsonschma doesn't work expected when I try the regular expressions: regular expressions.

The error message is: property "OpenKey" validation failed: failed to match pattern "^(\([0-9]{3}\))?[0-9]{3}-[0-9]{4}$" with "555-1212"

main function has more than 200 local variables

Hi, any help with this? Thanks ;-)

lua: /usr/local/share/lua/5.1/jsonschema/init.lua:188: [string "jsonschema:anonymous"]:3686: main function has more than 200 local variables
stack traceback:
        [C]: in function 'error'
        /usr/local/share/lua/5.1/jsonschema/init.lua:188: in function </usr/local/share/lua/5.1/jsonschema/init.lua:168>
        (tail call): ?
        .///compiled/abstract/minetest_mod/generator.lua:995: in main chunk
        [C]: in function 'require'
        ./check.lua:2: in main chunk
        [C]: ?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.