CMD-X

json

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