-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjson.lua
More file actions
55 lines (42 loc) · 950 Bytes
/
json.lua
File metadata and controls
55 lines (42 loc) · 950 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
local JSON = require("JSON")
local Json = {}
---@enum JsonType
JsonType = {
ARRAY = "%b[]",
DICTIONARY = "%b{}",
}
---@param str string
---@param outer_type JsonType?
---@return table?
function Json.decode(str, outer_type)
local s, e = str:find(outer_type or JsonType.DICTIONARY, nil, false)
if s == nil then
return nil
end
str = str:sub(s, e)
local decoded_obj = JSON:decode(str)
if type(decoded_obj) ~= "table" then
return nil
end
return decoded_obj
end
---@class encode_options
---@field pretty boolean
---@field indent string
---
---@param obj table
---@param options encode_options
---@return string?
function Json.encode(obj, options)
local encoded_obj = JSON:encode(obj, nil, options)
if encoded_obj == "[]" then
options = options or {}
if options.pretty then
return "{\n}"
else
return "{}"
end
end
return encoded_obj
end
return Json