generated from your-land/yl_template
your-land/yl_announcements#3 Adds basic JSON validation
This commit is contained in:
parent
f18532fcdb
commit
1a2c8507ba
32
internal.lua
32
internal.lua
@ -63,6 +63,36 @@ local function is_visible(filename) return (string.sub(filename, 1, 1) ~= ".") e
|
||||
|
||||
local function is_json(filename) return (filename:match("%.json$")) end
|
||||
|
||||
local function validate_json(content, schema)
|
||||
|
||||
-- Are all fields mentioned in the schema?
|
||||
for key, _ in pairs(content) do
|
||||
if schema[key] == nil then
|
||||
say("validate_json : Unexpected field in key = " .. dump(key))
|
||||
return false, "Unexpected field in " .. dump(key)
|
||||
end
|
||||
end
|
||||
|
||||
-- Are all fields of the expected type?
|
||||
for key, expected_type in pairs(schema) do
|
||||
if type(content[key]) ~= expected_type then
|
||||
say("validate_json : Validation error in key = " .. dump(key))
|
||||
return false, "Validation error in " .. dump(key) .. " not of type " .. dump(expected_type)
|
||||
end
|
||||
end
|
||||
|
||||
return true
|
||||
end
|
||||
|
||||
local schema = {
|
||||
id = "number",
|
||||
creation_date = "number",
|
||||
message = "string",
|
||||
frequency = "number",
|
||||
runtime = "number",
|
||||
owner = "string"
|
||||
}
|
||||
|
||||
local function load_all_data()
|
||||
-- Get all json files from savepath
|
||||
-- Excluding invisible
|
||||
@ -79,7 +109,7 @@ local function load_all_data()
|
||||
local filepath = get_filepath(filename)
|
||||
local success, content = load_json(filepath)
|
||||
|
||||
if success and content.id then
|
||||
if success and content.id and (validate_json(content, schema) == true) then
|
||||
good = good + 1
|
||||
data[content.id] = content
|
||||
else
|
||||
|
||||
Loading…
Reference in New Issue
Block a user