json.lua 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389
  1. --
  2. -- https://github.com/rxi/json.lua
  3. --
  4. -- Copyright (c) 2020 rxi
  5. --
  6. -- Permission is hereby granted, free of charge, to any person obtaining a copy of
  7. -- this software and associated documentation files (the "Software"), to deal in
  8. -- the Software without restriction, including without limitation the rights to
  9. -- use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
  10. -- of the Software, and to permit persons to whom the Software is furnished to do
  11. -- so, subject to the following conditions:
  12. --
  13. -- The above copyright notice and this permission notice shall be included in all
  14. -- copies or substantial portions of the Software.
  15. --
  16. -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17. -- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  18. -- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  19. -- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  20. -- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  21. -- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  22. -- SOFTWARE.
  23. --
  24. local json = { _version = "0.1.2" }
  25. -------------------------------------------------------------------------------
  26. -- Encode
  27. -------------------------------------------------------------------------------
  28. local encode
  29. local escape_char_map = {
  30. [ "\\" ] = "\\",
  31. [ "\"" ] = "\"",
  32. [ "\b" ] = "b",
  33. [ "\f" ] = "f",
  34. [ "\n" ] = "n",
  35. [ "\r" ] = "r",
  36. [ "\t" ] = "t",
  37. }
  38. local escape_char_map_inv = { [ "/" ] = "/" }
  39. for k, v in pairs(escape_char_map) do
  40. escape_char_map_inv[v] = k
  41. end
  42. local function escape_char(c)
  43. return "\\" .. (escape_char_map[c] or string.format("u%04x", c:byte()))
  44. end
  45. local function encode_nil(val)
  46. return "null"
  47. end
  48. local function encode_table(val, stack)
  49. local res = {}
  50. stack = stack or {}
  51. -- Circular reference?
  52. if stack[val] then error("circular reference") end
  53. stack[val] = true
  54. if rawget(val, 1) ~= nil or next(val) == nil then
  55. -- Treat as array -- check keys are valid and it is not sparse
  56. local n = 0
  57. for k in pairs(val) do
  58. if type(k) ~= "number" then
  59. error("invalid table: mixed or invalid key types")
  60. end
  61. n = n + 1
  62. end
  63. if n ~= #val then
  64. error("invalid table: sparse array")
  65. end
  66. -- Encode
  67. for i, v in ipairs(val) do
  68. table.insert(res, encode(v, stack))
  69. end
  70. stack[val] = nil
  71. return "[" .. table.concat(res, ",") .. "]"
  72. else
  73. -- Treat as an object
  74. for k, v in pairs(val) do
  75. if type(k) ~= "string" then
  76. error("invalid table: mixed or invalid key types")
  77. end
  78. table.insert(res, encode(k, stack) .. ":" .. encode(v, stack))
  79. end
  80. stack[val] = nil
  81. return "{" .. table.concat(res, ",") .. "}"
  82. end
  83. end
  84. local function encode_string(val)
  85. return '"' .. val:gsub('[%z\1-\31\\"]', escape_char) .. '"'
  86. end
  87. local function encode_number(val)
  88. -- Check for NaN, -inf and inf
  89. if val ~= val or val <= -math.huge or val >= math.huge then
  90. error("unexpected number value '" .. tostring(val) .. "'")
  91. end
  92. return string.format("%.14g", val)
  93. end
  94. local type_func_map = {
  95. [ "nil" ] = encode_nil,
  96. [ "table" ] = encode_table,
  97. [ "string" ] = encode_string,
  98. [ "number" ] = encode_number,
  99. [ "boolean" ] = tostring,
  100. }
  101. encode = function(val, stack)
  102. local t = type(val)
  103. local f = type_func_map[t]
  104. if f then
  105. return f(val, stack)
  106. end
  107. error("unexpected type '" .. t .. "'")
  108. end
  109. function json.encode(val)
  110. return ( encode(val) )
  111. end
  112. -------------------------------------------------------------------------------
  113. -- Decode
  114. -------------------------------------------------------------------------------
  115. local parse
  116. local function create_set(...)
  117. local res = {}
  118. for i = 1, select("#", ...) do
  119. res[ select(i, ...) ] = true
  120. end
  121. return res
  122. end
  123. local space_chars = create_set(" ", "\t", "\r", "\n")
  124. local delim_chars = create_set(" ", "\t", "\r", "\n", "]", "}", ",")
  125. local escape_chars = create_set("\\", "/", '"', "b", "f", "n", "r", "t", "u")
  126. local literals = create_set("true", "false", "null")
  127. local literal_map = {
  128. [ "true" ] = true,
  129. [ "false" ] = false,
  130. [ "null" ] = nil,
  131. }
  132. local function next_char(str, idx, set, negate)
  133. for i = idx, #str do
  134. if set[str:sub(i, i)] ~= negate then
  135. return i
  136. end
  137. end
  138. return #str + 1
  139. end
  140. local function decode_error(str, idx, msg)
  141. local line_count = 1
  142. local col_count = 1
  143. for i = 1, idx - 1 do
  144. col_count = col_count + 1
  145. if str:sub(i, i) == "\n" then
  146. line_count = line_count + 1
  147. col_count = 1
  148. end
  149. end
  150. error( string.format("%s at line %d col %d", msg, line_count, col_count) )
  151. end
  152. local function codepoint_to_utf8(n)
  153. -- http://scripts.sil.org/cms/scripts/page.php?site_id=nrsi&id=iws-appendixa
  154. local f = math.floor
  155. if n <= 0x7f then
  156. return string.char(n)
  157. elseif n <= 0x7ff then
  158. return string.char(f(n / 64) + 192, n % 64 + 128)
  159. elseif n <= 0xffff then
  160. return string.char(f(n / 4096) + 224, f(n % 4096 / 64) + 128, n % 64 + 128)
  161. elseif n <= 0x10ffff then
  162. return string.char(f(n / 262144) + 240, f(n % 262144 / 4096) + 128,
  163. f(n % 4096 / 64) + 128, n % 64 + 128)
  164. end
  165. error( string.format("invalid unicode codepoint '%x'", n) )
  166. end
  167. local function parse_unicode_escape(s)
  168. local n1 = tonumber( s:sub(1, 4), 16 )
  169. local n2 = tonumber( s:sub(7, 10), 16 )
  170. -- Surrogate pair?
  171. if n2 then
  172. return codepoint_to_utf8((n1 - 0xd800) * 0x400 + (n2 - 0xdc00) + 0x10000)
  173. else
  174. return codepoint_to_utf8(n1)
  175. end
  176. end
  177. local function parse_string(str, i)
  178. local res = ""
  179. local j = i + 1
  180. local k = j
  181. while j <= #str do
  182. local x = str:byte(j)
  183. if x < 32 then
  184. decode_error(str, j, "control character in string")
  185. elseif x == 92 then -- `\`: Escape
  186. res = res .. str:sub(k, j - 1)
  187. j = j + 1
  188. local c = str:sub(j, j)
  189. if c == "u" then
  190. local hex = str:match("^[dD][89aAbB]%x%x\\u%x%x%x%x", j + 1)
  191. or str:match("^%x%x%x%x", j + 1)
  192. or decode_error(str, j - 1, "invalid unicode escape in string")
  193. res = res .. parse_unicode_escape(hex)
  194. j = j + #hex
  195. else
  196. if not escape_chars[c] then
  197. decode_error(str, j - 1, "invalid escape char '" .. c .. "' in string")
  198. end
  199. res = res .. escape_char_map_inv[c]
  200. end
  201. k = j + 1
  202. elseif x == 34 then -- `"`: End of string
  203. res = res .. str:sub(k, j - 1)
  204. return res, j + 1
  205. end
  206. j = j + 1
  207. end
  208. decode_error(str, i, "expected closing quote for string")
  209. end
  210. local function parse_number(str, i)
  211. local x = next_char(str, i, delim_chars)
  212. local s = str:sub(i, x - 1)
  213. local n = tonumber(s)
  214. if not n then
  215. decode_error(str, i, "invalid number '" .. s .. "'")
  216. end
  217. return n, x
  218. end
  219. local function parse_literal(str, i)
  220. local x = next_char(str, i, delim_chars)
  221. local word = str:sub(i, x - 1)
  222. if not literals[word] then
  223. decode_error(str, i, "invalid literal '" .. word .. "'")
  224. end
  225. return literal_map[word], x
  226. end
  227. local function parse_array(str, i)
  228. local res = {}
  229. local n = 1
  230. i = i + 1
  231. while 1 do
  232. local x
  233. i = next_char(str, i, space_chars, true)
  234. -- Empty / end of array?
  235. if str:sub(i, i) == "]" then
  236. i = i + 1
  237. break
  238. end
  239. -- Read token
  240. x, i = parse(str, i)
  241. res[n] = x
  242. n = n + 1
  243. -- Next token
  244. i = next_char(str, i, space_chars, true)
  245. local chr = str:sub(i, i)
  246. i = i + 1
  247. if chr == "]" then break end
  248. if chr ~= "," then decode_error(str, i, "expected ']' or ','") end
  249. end
  250. return res, i
  251. end
  252. local function parse_object(str, i)
  253. local res = {}
  254. i = i + 1
  255. while 1 do
  256. local key, val
  257. i = next_char(str, i, space_chars, true)
  258. -- Empty / end of object?
  259. if str:sub(i, i) == "}" then
  260. i = i + 1
  261. break
  262. end
  263. -- Read key
  264. if str:sub(i, i) ~= '"' then
  265. decode_error(str, i, "expected string for key")
  266. end
  267. key, i = parse(str, i)
  268. -- Read ':' delimiter
  269. i = next_char(str, i, space_chars, true)
  270. if str:sub(i, i) ~= ":" then
  271. decode_error(str, i, "expected ':' after key")
  272. end
  273. i = next_char(str, i + 1, space_chars, true)
  274. -- Read value
  275. val, i = parse(str, i)
  276. -- Set
  277. res[key] = val
  278. -- Next token
  279. i = next_char(str, i, space_chars, true)
  280. local chr = str:sub(i, i)
  281. i = i + 1
  282. if chr == "}" then break end
  283. if chr ~= "," then decode_error(str, i, "expected '}' or ','") end
  284. end
  285. return res, i
  286. end
  287. local char_func_map = {
  288. [ '"' ] = parse_string,
  289. [ "0" ] = parse_number,
  290. [ "1" ] = parse_number,
  291. [ "2" ] = parse_number,
  292. [ "3" ] = parse_number,
  293. [ "4" ] = parse_number,
  294. [ "5" ] = parse_number,
  295. [ "6" ] = parse_number,
  296. [ "7" ] = parse_number,
  297. [ "8" ] = parse_number,
  298. [ "9" ] = parse_number,
  299. [ "-" ] = parse_number,
  300. [ "t" ] = parse_literal,
  301. [ "f" ] = parse_literal,
  302. [ "n" ] = parse_literal,
  303. [ "[" ] = parse_array,
  304. [ "{" ] = parse_object,
  305. }
  306. parse = function(str, idx)
  307. local chr = str:sub(idx, idx)
  308. local f = char_func_map[chr]
  309. if f then
  310. return f(str, idx)
  311. end
  312. decode_error(str, idx, "unexpected character '" .. chr .. "'")
  313. end
  314. function json.decode(str)
  315. if type(str) ~= "string" then
  316. error("expected argument of type string, got " .. type(str))
  317. end
  318. local res, idx = parse(str, next_char(str, 1, space_chars, true))
  319. idx = next_char(str, idx, space_chars, true)
  320. if idx <= #str then
  321. decode_error(str, idx, "trailing garbage")
  322. end
  323. return res
  324. end
  325. return json