Add JSON API (#729)

* Add JSON API
This commit is contained in:
Aleksi Juvani 2017-04-04 19:02:59 +03:00 committed by Tom van Dijck
parent 896d61e3ab
commit 479d51af81
5 changed files with 1629 additions and 0 deletions

View File

@ -22,6 +22,8 @@
"base/moduledownloader.lua",
"base/semver.lua",
"base/http.lua",
"base/json.lua",
"base/jsonwrapper.lua",
-- configuration data
"base/field.lua",

1548
src/base/json.lua Normal file

File diff suppressed because it is too large Load Diff

46
src/base/jsonwrapper.lua Normal file
View File

@ -0,0 +1,46 @@
--
-- jsonwrapper.lua
-- Provides JSON encoding and decoding API by wrapping a third-party JSON library
-- Copyright (c) 2017 Jason Perkins and the Premake project
--
json = {}
local implementation = dofile('json.lua')
local err
function implementation.assert(condition, message)
if not condition then
err = message
end
-- The JSON library we're using assumes that encode error handlers will
-- abort on error. It doesn't have the same assumption for decode error
-- handlers, but we're using this same function for both.
assert(condition, message)
end
function json.encode(value)
err = nil
local success, result = pcall(implementation.encode, implementation, value)
if not success then
return nil, err
end
return result
end
function json.decode(value)
err = nil
local success, result = pcall(implementation.decode, implementation, value)
if not success then
return nil, err
end
return result
end

View File

@ -18,6 +18,7 @@ return {
"base/test_uuid.lua",
"base/test_versions.lua",
"base/test_http.lua",
"base/test_json.lua",
-- Workspace object tests
"workspace/test_eachconfig.lua",

32
tests/base/test_json.lua Normal file
View File

@ -0,0 +1,32 @@
--
-- tests/base/test_json.lua
-- Tests the json API
-- Copyright (c) 2017 Jason Perkins and the Premake project
--
local p = premake
local suite = test.declare("premake_json")
function suite.json_encode()
local result = json.encode({foo = "bar"})
result = result:gsub('%s*', ''),
test.isequal(result, '{"foo":"bar"}')
end
function suite.json_decode()
local result = json.decode('{ "foo": "bar" }')
test.isequal(result, { foo = "bar" })
end
function suite.json_encode_error()
local result, err = json.encode({ fubar = function() end })
test.isnil(result)
test.isequal(type(err), "string")
end
function suite.json_decode_error()
local result, err = json.decode("fubar string")
test.isnil(result)
test.isequal(type(err), "string")
end