Guest User

Untitled

a guest
Nov 26th, 2015
381
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 36.23 KB | None | 0 0
  1. --JSON encoder/decoder
  2. local JSON = loadstring([[
  3. -- -*- coding: utf-8 -*-
  4. --
  5. -- Simple JSON encoding and decoding in pure Lua.
  6. --
  7. -- Copyright 2010-2014 Jeffrey Friedl
  8. -- http://regex.info/blog/
  9. --
  10. -- Latest version: http://regex.info/blog/lua/json
  11. --
  12. -- This code is released under a Creative Commons CC-BY "Attribution" License:
  13. -- http://creativecommons.org/licenses/by/3.0/deed.en_US
  14. --
  15. -- It can be used for any purpose so long as the copyright notice above,
  16. -- the web-page links above, and the 'AUTHOR_NOTE' string below are
  17. -- maintained. Enjoy.
  18. --
  19. local VERSION = 20141223.14 -- version history at end of file
  20. local AUTHOR_NOTE = "-[ JSON.lua package by Jeffrey Friedl (http://regex.info/blog/lua/json) version 20141223.14 ]-"
  21.  
  22. --
  23. -- The 'AUTHOR_NOTE' variable exists so that information about the source
  24. -- of the package is maintained even in compiled versions. It's also
  25. -- included in OBJDEF below mostly to quiet warnings about unused variables.
  26. --
  27. local OBJDEF = {
  28.    VERSION      = VERSION,
  29.    AUTHOR_NOTE  = AUTHOR_NOTE,
  30. }
  31.  
  32.  
  33. --
  34. -- Simple JSON encoding and decoding in pure Lua.
  35. -- http://www.json.org/
  36. --
  37. --
  38. --   JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
  39. --
  40. --   local lua_value = JSON:decode(raw_json_text)
  41. --
  42. --   local raw_json_text    = JSON:encode(lua_table_or_value)
  43. --   local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability
  44. --
  45. --
  46. --
  47. -- DECODING (from a JSON string to a Lua table)
  48. --
  49. --
  50. --   JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
  51. --
  52. --   local lua_value = JSON:decode(raw_json_text)
  53. --
  54. --   If the JSON text is for an object or an array, e.g.
  55. --     { "what": "books", "count": 3 }
  56. --   or
  57. --     [ "Larry", "Curly", "Moe" ]
  58. --
  59. --   the result is a Lua table, e.g.
  60. --     { what = "books", count = 3 }
  61. --   or
  62. --     { "Larry", "Curly", "Moe" }
  63. --
  64. --
  65. --   The encode and decode routines accept an optional second argument,
  66. --   "etc", which is not used during encoding or decoding, but upon error
  67. --   is passed along to error handlers. It can be of any type (including nil).
  68. --
  69. --
  70. --
  71. -- ERROR HANDLING
  72. --
  73. --   With most errors during decoding, this code calls
  74. --
  75. --      JSON:onDecodeError(message, text, location, etc)
  76. --
  77. --   with a message about the error, and if known, the JSON text being
  78. --   parsed and the byte count where the problem was discovered. You can
  79. --   replace the default JSON:onDecodeError() with your own function.
  80. --
  81. --   The default onDecodeError() merely augments the message with data
  82. --   about the text and the location if known (and if a second 'etc'
  83. --   argument had been provided to decode(), its value is tacked onto the
  84. --   message as well), and then calls JSON.assert(), which itself defaults
  85. --   to Lua's built-in assert(), and can also be overridden.
  86. --
  87. --   For example, in an Adobe Lightroom plugin, you might use something like
  88. --
  89. --          function JSON:onDecodeError(message, text, location, etc)
  90. --             LrErrors.throwUserError("Internal Error: invalid JSON data")
  91. --          end
  92. --
  93. --   or even just
  94. --
  95. --          function JSON.assert(message)
  96. --             LrErrors.throwUserError("Internal Error: " .. message)
  97. --          end
  98. --
  99. --   If JSON:decode() is passed a nil, this is called instead:
  100. --
  101. --      JSON:onDecodeOfNilError(message, nil, nil, etc)
  102. --
  103. --   and if JSON:decode() is passed HTML instead of JSON, this is called:
  104. --
  105. --      JSON:onDecodeOfHTMLError(message, text, nil, etc)
  106. --
  107. --   The use of the fourth 'etc' argument allows stronger coordination
  108. --   between decoding and error reporting, especially when you provide your
  109. --   own error-handling routines. Continuing with the the Adobe Lightroom
  110. --   plugin example:
  111. --
  112. --          function JSON:onDecodeError(message, text, location, etc)
  113. --             local note = "Internal Error: invalid JSON data"
  114. --             if type(etc) = 'table' and etc.photo then
  115. --                note = note .. " while processing for " .. etc.photo:getFormattedMetadata('fileName')
  116. --             end
  117. --             LrErrors.throwUserError(note)
  118. --          end
  119. --
  120. --            :
  121. --            :
  122. --
  123. --          for i, photo in ipairs(photosToProcess) do
  124. --               :
  125. --               :
  126. --               local data = JSON:decode(someJsonText, { photo = photo })
  127. --               :
  128. --               :
  129. --          end
  130. --
  131. --
  132. --
  133. --
  134. --
  135. -- DECODING AND STRICT TYPES
  136. --
  137. --   Because both JSON objects and JSON arrays are converted to Lua tables,
  138. --   it's not normally possible to tell which original JSON type a
  139. --   particular Lua table was derived from, or guarantee decode-encode
  140. --   round-trip equivalency.
  141. --
  142. --   However, if you enable strictTypes, e.g.
  143. --
  144. --      JSON = assert(loadfile "JSON.lua")() --load the routines
  145. --      JSON.strictTypes = true
  146. --
  147. --   then the Lua table resulting from the decoding of a JSON object or
  148. --   JSON array is marked via Lua metatable, so that when re-encoded with
  149. --   JSON:encode() it ends up as the appropriate JSON type.
  150. --
  151. --   (This is not the default because other routines may not work well with
  152. --   tables that have a metatable set, for example, Lightroom API calls.)
  153. --
  154. --
  155. -- ENCODING (from a lua table to a JSON string)
  156. --
  157. --   JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
  158. --
  159. --   local raw_json_text    = JSON:encode(lua_table_or_value)
  160. --   local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability
  161. --   local custom_pretty    = JSON:encode(lua_table_or_value, etc, { pretty = true, indent = "|  ", align_keys = false })
  162. --
  163. --   On error during encoding, this code calls:
  164. --
  165. --     JSON:onEncodeError(message, etc)
  166. --
  167. --   which you can override in your local JSON object.
  168. --
  169. --   The 'etc' in the error call is the second argument to encode()
  170. --   and encode_pretty(), or nil if it wasn't provided.
  171. --
  172. --
  173. -- PRETTY-PRINTING
  174. --
  175. --   An optional third argument, a table of options, allows a bit of
  176. --   configuration about how the encoding takes place:
  177. --
  178. --     pretty = JSON:encode(val, etc, {
  179. --                                       pretty = true,      -- if false, no other options matter
  180. --                                       indent = "   ",     -- this provides for a three-space indent per nesting level
  181. --                                       align_keys = false, -- see below
  182. --                                     })
  183. --
  184. --   encode() and encode_pretty() are identical except that encode_pretty()
  185. --   provides a default options table if none given in the call:
  186. --
  187. --       { pretty = true, align_keys = false, indent = "  " }
  188. --
  189. --   For example, if
  190. --
  191. --      JSON:encode(data)
  192. --
  193. --   produces:
  194. --
  195. --      {"city":"Kyoto","climate":{"avg_temp":16,"humidity":"high","snowfall":"minimal"},"country":"Japan","wards":11}
  196. --
  197. --   then
  198. --
  199. --      JSON:encode_pretty(data)
  200. --
  201. --   produces:
  202. --
  203. --      {
  204. --        "city": "Kyoto",
  205. --        "climate": {
  206. --          "avg_temp": 16,
  207. --          "humidity": "high",
  208. --          "snowfall": "minimal"
  209. --        },
  210. --        "country": "Japan",
  211. --        "wards": 11
  212. --      }
  213. --
  214. --   The following three lines return identical results:
  215. --       JSON:encode_pretty(data)
  216. --       JSON:encode_pretty(data, nil, { pretty = true, align_keys = false, indent = "  " })
  217. --       JSON:encode       (data, nil, { pretty = true, align_keys = false, indent = "  " })
  218. --
  219. --   An example of setting your own indent string:
  220. --
  221. --     JSON:encode_pretty(data, nil, { pretty = true, indent = "|    " })
  222. --
  223. --   produces:
  224. --
  225. --      {
  226. --      |    "city": "Kyoto",
  227. --      |    "climate": {
  228. --      |    |    "avg_temp": 16,
  229. --      |    |    "humidity": "high",
  230. --      |    |    "snowfall": "minimal"
  231. --      |    },
  232. --      |    "country": "Japan",
  233. --      |    "wards": 11
  234. --      }
  235. --
  236. --   An example of setting align_keys to true:
  237. --
  238. --     JSON:encode_pretty(data, nil, { pretty = true, indent = "  ", align_keys = true })
  239. --
  240. --   produces:
  241. --
  242. --      {
  243. --           "city": "Kyoto",
  244. --        "climate": {
  245. --                     "avg_temp": 16,
  246. --                     "humidity": "high",
  247. --                     "snowfall": "minimal"
  248. --                   },
  249. --        "country": "Japan",
  250. --          "wards": 11
  251. --      }
  252. --
  253. --   which I must admit is kinda ugly, sorry. This was the default for
  254. --   encode_pretty() prior to version 20141223.14.
  255. --
  256. --
  257. --  AMBIGUOUS SITUATIONS DURING THE ENCODING
  258. --
  259. --   During the encode, if a Lua table being encoded contains both string
  260. --   and numeric keys, it fits neither JSON's idea of an object, nor its
  261. --   idea of an array. To get around this, when any string key exists (or
  262. --   when non-positive numeric keys exist), numeric keys are converted to
  263. --   strings.
  264. --
  265. --   For example,
  266. --     JSON:encode({ "one", "two", "three", SOMESTRING = "some string" }))
  267. --   produces the JSON object
  268. --     {"1":"one","2":"two","3":"three","SOMESTRING":"some string"}
  269. --
  270. --   To prohibit this conversion and instead make it an error condition, set
  271. --      JSON.noKeyConversion = true
  272. --
  273.  
  274.  
  275.  
  276.  
  277. --
  278. -- SUMMARY OF METHODS YOU CAN OVERRIDE IN YOUR LOCAL LUA JSON OBJECT
  279. --
  280. --    assert
  281. --    onDecodeError
  282. --    onDecodeOfNilError
  283. --    onDecodeOfHTMLError
  284. --    onEncodeError
  285. --
  286. --  If you want to create a separate Lua JSON object with its own error handlers,
  287. --  you can reload JSON.lua or use the :new() method.
  288. --
  289. ---------------------------------------------------------------------------
  290.  
  291. local default_pretty_indent  = "  "
  292. local default_pretty_options = { pretty = true, align_keys = false, indent = default_pretty_indent }
  293.  
  294. local isArray  = { __tostring = function() return "JSON array"  end }    isArray.__index  = isArray
  295. local isObject = { __tostring = function() return "JSON object" end }    isObject.__index = isObject
  296.  
  297.  
  298. function OBJDEF:newArray(tbl)
  299.    return setmetatable(tbl or {}, isArray)
  300. end
  301.  
  302. function OBJDEF:newObject(tbl)
  303.    return setmetatable(tbl or {}, isObject)
  304. end
  305.  
  306. local function unicode_codepoint_as_utf8(codepoint)
  307.    --
  308.    -- codepoint is a number
  309.    --
  310.    if codepoint <= 127 then
  311.       return string.char(codepoint)
  312.  
  313.    elseif codepoint <= 2047 then
  314.       --
  315.       -- 110yyyxx 10xxxxxx         <-- useful notation from http://en.wikipedia.org/wiki/Utf8
  316.       --
  317.       local highpart = math.floor(codepoint / 0x40)
  318.       local lowpart  = codepoint - (0x40 * highpart)
  319.       return string.char(0xC0 + highpart,
  320.                          0x80 + lowpart)
  321.  
  322.    elseif codepoint <= 65535 then
  323.       --
  324.       -- 1110yyyy 10yyyyxx 10xxxxxx
  325.       --
  326.       local highpart  = math.floor(codepoint / 0x1000)
  327.       local remainder = codepoint - 0x1000 * highpart
  328.       local midpart   = math.floor(remainder / 0x40)
  329.       local lowpart   = remainder - 0x40 * midpart
  330.  
  331.       highpart = 0xE0 + highpart
  332.       midpart  = 0x80 + midpart
  333.       lowpart  = 0x80 + lowpart
  334.  
  335.       --
  336.       -- Check for an invalid character (thanks Andy R. at Adobe).
  337.       -- See table 3.7, page 93, in http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf#G28070
  338.       --
  339.       if ( highpart == 0xE0 and midpart < 0xA0 ) or
  340.          ( highpart == 0xED and midpart > 0x9F ) or
  341.          ( highpart == 0xF0 and midpart < 0x90 ) or
  342.          ( highpart == 0xF4 and midpart > 0x8F )
  343.       then
  344.          return "?"
  345.       else
  346.          return string.char(highpart,
  347.                             midpart,
  348.                             lowpart)
  349.       end
  350.  
  351.    else
  352.       --
  353.       -- 11110zzz 10zzyyyy 10yyyyxx 10xxxxxx
  354.       --
  355.       local highpart  = math.floor(codepoint / 0x40000)
  356.       local remainder = codepoint - 0x40000 * highpart
  357.       local midA      = math.floor(remainder / 0x1000)
  358.       remainder       = remainder - 0x1000 * midA
  359.       local midB      = math.floor(remainder / 0x40)
  360.       local lowpart   = remainder - 0x40 * midB
  361.  
  362.       return string.char(0xF0 + highpart,
  363.                          0x80 + midA,
  364.                          0x80 + midB,
  365.                          0x80 + lowpart)
  366.    end
  367. end
  368.  
  369. function OBJDEF:onDecodeError(message, text, location, etc)
  370.    if text then
  371.       if location then
  372.          message = string.format("%s at char %d of: %s", message, location, text)
  373.       else
  374.          message = string.format("%s: %s", message, text)
  375.       end
  376.    end
  377.  
  378.    if etc ~= nil then
  379.       message = message .. " (" .. OBJDEF:encode(etc) .. ")"
  380.    end
  381.  
  382.    if self.assert then
  383.       self.assert(false, message)
  384.    else
  385.       assert(false, message)
  386.    end
  387. end
  388.  
  389. OBJDEF.onDecodeOfNilError  = OBJDEF.onDecodeError
  390. OBJDEF.onDecodeOfHTMLError = OBJDEF.onDecodeError
  391.  
  392. function OBJDEF:onEncodeError(message, etc)
  393.    if etc ~= nil then
  394.       message = message .. " (" .. OBJDEF:encode(etc) .. ")"
  395.    end
  396.  
  397.    if self.assert then
  398.       self.assert(false, message)
  399.    else
  400.       assert(false, message)
  401.    end
  402. end
  403.  
  404. local function grok_number(self, text, start, etc)
  405.    --
  406.    -- Grab the integer part
  407.    --
  408.    local integer_part = text:match('^-?[1-9]%d*', start)
  409.                      or text:match("^-?0",        start)
  410.  
  411.    if not integer_part then
  412.       self:onDecodeError("expected number", text, start, etc)
  413.    end
  414.  
  415.    local i = start + integer_part:len()
  416.  
  417.    --
  418.    -- Grab an optional decimal part
  419.    --
  420.    local decimal_part = text:match('^%.%d+', i) or ""
  421.  
  422.    i = i + decimal_part:len()
  423.  
  424.    --
  425.    -- Grab an optional exponential part
  426.    --
  427.    local exponent_part = text:match('^[eE][-+]?%d+', i) or ""
  428.  
  429.    i = i + exponent_part:len()
  430.  
  431.    local full_number_text = integer_part .. decimal_part .. exponent_part
  432.    local as_number = tonumber(full_number_text)
  433.  
  434.    if not as_number then
  435.       self:onDecodeError("bad number", text, start, etc)
  436.    end
  437.  
  438.    return as_number, i
  439. end
  440.  
  441.  
  442. local function grok_string(self, text, start, etc)
  443.  
  444.    if text:sub(start,start) ~= '"' then
  445.       self:onDecodeError("expected string's opening quote", text, start, etc)
  446.    end
  447.  
  448.    local i = start + 1 -- +1 to bypass the initial quote
  449.    local text_len = text:len()
  450.    local VALUE = ""
  451.    while i <= text_len do
  452.       local c = text:sub(i,i)
  453.       if c == '"' then
  454.          return VALUE, i + 1
  455.       end
  456.       if c ~= '\\' then
  457.          VALUE = VALUE .. c
  458.          i = i + 1
  459.       elseif text:match('^\\b', i) then
  460.          VALUE = VALUE .. "\b"
  461.          i = i + 2
  462.       elseif text:match('^\\f', i) then
  463.          VALUE = VALUE .. "\f"
  464.          i = i + 2
  465.       elseif text:match('^\\n', i) then
  466.          VALUE = VALUE .. "\n"
  467.          i = i + 2
  468.       elseif text:match('^\\r', i) then
  469.          VALUE = VALUE .. "\r"
  470.          i = i + 2
  471.       elseif text:match('^\\t', i) then
  472.          VALUE = VALUE .. "\t"
  473.          i = i + 2
  474.       else
  475.          local hex = text:match('^\\u([0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i)
  476.          if hex then
  477.             i = i + 6 -- bypass what we just read
  478.  
  479.             -- We have a Unicode codepoint. It could be standalone, or if in the proper range and
  480.             -- followed by another in a specific range, it'll be a two-code surrogate pair.
  481.             local codepoint = tonumber(hex, 16)
  482.             if codepoint >= 0xD800 and codepoint <= 0xDBFF then
  483.                -- it's a hi surrogate... see whether we have a following low
  484.                local lo_surrogate = text:match('^\\u([dD][cdefCDEF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i)
  485.                if lo_surrogate then
  486.                   i = i + 6 -- bypass the low surrogate we just read
  487.                   codepoint = 0x2400 + (codepoint - 0xD800) * 0x400 + tonumber(lo_surrogate, 16)
  488.                else
  489.                   -- not a proper low, so we'll just leave the first codepoint as is and spit it out.
  490.                end
  491.             end
  492.             VALUE = VALUE .. unicode_codepoint_as_utf8(codepoint)
  493.  
  494.          else
  495.  
  496.             -- just pass through what's escaped
  497.             VALUE = VALUE .. text:match('^\\(.)', i)
  498.             i = i + 2
  499.          end
  500.       end
  501.    end
  502.  
  503.    self:onDecodeError("unclosed string", text, start, etc)
  504. end
  505.  
  506. local function skip_whitespace(text, start)
  507.  
  508.    local _, match_end = text:find("^[ \n\r\t]+", start) -- [http://www.ietf.org/rfc/rfc4627.txt] Section 2
  509.    if match_end then
  510.       return match_end + 1
  511.    else
  512.       return start
  513.    end
  514. end
  515.  
  516. local grok_one -- assigned later
  517.  
  518. local function grok_object(self, text, start, etc)
  519.    if text:sub(start,start) ~= '{' then
  520.       self:onDecodeError("expected '{'", text, start, etc)
  521.    end
  522.  
  523.    local i = skip_whitespace(text, start + 1) -- +1 to skip the '{'
  524.  
  525.    local VALUE = self.strictTypes and self:newObject { } or { }
  526.  
  527.    if text:sub(i,i) == '}' then
  528.       return VALUE, i + 1
  529.    end
  530.    local text_len = text:len()
  531.    while i <= text_len do
  532.       local key, new_i = grok_string(self, text, i, etc)
  533.  
  534.       i = skip_whitespace(text, new_i)
  535.  
  536.       if text:sub(i, i) ~= ':' then
  537.          self:onDecodeError("expected colon", text, i, etc)
  538.       end
  539.  
  540.       i = skip_whitespace(text, i + 1)
  541.  
  542.       local new_val, new_i = grok_one(self, text, i)
  543.  
  544.       VALUE[key] = new_val
  545.  
  546.       --
  547.       -- Expect now either '}' to end things, or a ',' to allow us to continue.
  548.       --
  549.       i = skip_whitespace(text, new_i)
  550.  
  551.       local c = text:sub(i,i)
  552.  
  553.       if c == '}' then
  554.          return VALUE, i + 1
  555.       end
  556.  
  557.       if text:sub(i, i) ~= ',' then
  558.          self:onDecodeError("expected comma or '}'", text, i, etc)
  559.       end
  560.  
  561.       i = skip_whitespace(text, i + 1)
  562.    end
  563.  
  564.    self:onDecodeError("unclosed '{'", text, start, etc)
  565. end
  566.  
  567. local function grok_array(self, text, start, etc)
  568.    if text:sub(start,start) ~= '[' then
  569.       self:onDecodeError("expected '['", text, start, etc)
  570.    end
  571.  
  572.    local i = skip_whitespace(text, start + 1) -- +1 to skip the '['
  573.    local VALUE = self.strictTypes and self:newArray { } or { }
  574.    if text:sub(i,i) == ']' then
  575.       return VALUE, i + 1
  576.    end
  577.  
  578.    local VALUE_INDEX = 1
  579.  
  580.    local text_len = text:len()
  581.    while i <= text_len do
  582.       local val, new_i = grok_one(self, text, i)
  583.  
  584.       -- can't table.insert(VALUE, val) here because it's a no-op if val is nil
  585.       VALUE[VALUE_INDEX] = val
  586.       VALUE_INDEX = VALUE_INDEX + 1
  587.  
  588.       i = skip_whitespace(text, new_i)
  589.  
  590.       --
  591.       -- Expect now either ']' to end things, or a ',' to allow us to continue.
  592.       --
  593.       local c = text:sub(i,i)
  594.       if c == ']' then
  595.          return VALUE, i + 1
  596.       end
  597.       if text:sub(i, i) ~= ',' then
  598.          self:onDecodeError("expected comma or '['", text, i, etc)
  599.       end
  600.       i = skip_whitespace(text, i + 1)
  601.    end
  602.    self:onDecodeError("unclosed '['", text, start, etc)
  603. end
  604.  
  605.  
  606. grok_one = function(self, text, start, etc)
  607.    -- Skip any whitespace
  608.    start = skip_whitespace(text, start)
  609.  
  610.    if start > text:len() then
  611.       self:onDecodeError("unexpected end of string", text, nil, etc)
  612.    end
  613.  
  614.    if text:find('^"', start) then
  615.       return grok_string(self, text, start, etc)
  616.  
  617.    elseif text:find('^[-0123456789 ]', start) then
  618.       return grok_number(self, text, start, etc)
  619.  
  620.    elseif text:find('^%{', start) then
  621.       return grok_object(self, text, start, etc)
  622.  
  623.    elseif text:find('^%[', start) then
  624.       return grok_array(self, text, start, etc)
  625.  
  626.    elseif text:find('^true', start) then
  627.       return true, start + 4
  628.  
  629.    elseif text:find('^false', start) then
  630.       return false, start + 5
  631.  
  632.    elseif text:find('^null', start) then
  633.       return nil, start + 4
  634.  
  635.    else
  636.       self:onDecodeError("can't parse JSON", text, start, etc)
  637.    end
  638. end
  639.  
  640. function OBJDEF:decode(text, etc)
  641.    if type(self) ~= 'table' or self.__index ~= OBJDEF then
  642.       OBJDEF:onDecodeError("JSON:decode must be called in method format", nil, nil, etc)
  643.    end
  644.  
  645.    if text == nil then
  646.       self:onDecodeOfNilError(string.format("nil passed to JSON:decode()"), nil, nil, etc)
  647.    elseif type(text) ~= 'string' then
  648.       self:onDecodeError(string.format("expected string argument to JSON:decode(), got %s", type(text)), nil, nil, etc)
  649.    end
  650.  
  651.    if text:match('^%s*$') then
  652.       return nil
  653.    end
  654.  
  655.    if text:match('^%s*<') then
  656.       -- Can't be JSON... we'll assume it's HTML
  657.       self:onDecodeOfHTMLError(string.format("html passed to JSON:decode()"), text, nil, etc)
  658.    end
  659.  
  660.    --
  661.    -- Ensure that it's not UTF-32 or UTF-16.
  662.    -- Those are perfectly valid encodings for JSON (as per RFC 4627 section 3),
  663.    -- but this package can't handle them.
  664.    --
  665.    if text:sub(1,1):byte() == 0 or (text:len() >= 2 and text:sub(2,2):byte() == 0) then
  666.       self:onDecodeError("JSON package groks only UTF-8, sorry", text, nil, etc)
  667.    end
  668.  
  669.    local success, value = pcall(grok_one, self, text, 1, etc)
  670.  
  671.    if success then
  672.       return value
  673.    else
  674.       -- if JSON:onDecodeError() didn't abort out of the pcall, we'll have received the error message here as "value", so pass it along as an assert.
  675.       if self.assert then
  676.          self.assert(false, value)
  677.       else
  678.          assert(false, value)
  679.       end
  680.       -- and if we're still here, return a nil and throw the error message on as a second arg
  681.       return nil, value
  682.    end
  683. end
  684.  
  685. local function backslash_replacement_function(c)
  686.    if c == "\n" then
  687.       return "\\n"
  688.    elseif c == "\r" then
  689.       return "\\r"
  690.    elseif c == "\t" then
  691.       return "\\t"
  692.    elseif c == "\b" then
  693.       return "\\b"
  694.    elseif c == "\f" then
  695.       return "\\f"
  696.    elseif c == '"' then
  697.       return '\\"'
  698.    elseif c == '\\' then
  699.       return '\\\\'
  700.    else
  701.       return string.format("\\u%04x", c:byte())
  702.    end
  703. end
  704.  
  705. local chars_to_be_escaped_in_JSON_string
  706.    = '['
  707.    ..    '"'    -- class sub-pattern to match a double quote
  708.    ..    '%\\'  -- class sub-pattern to match a backslash
  709.    ..    '%z'   -- class sub-pattern to match a null
  710.    ..    '\001' .. '-' .. '\031' -- class sub-pattern to match control characters
  711.    .. ']'
  712.  
  713. local function json_string_literal(value)
  714.    local newval = value:gsub(chars_to_be_escaped_in_JSON_string, backslash_replacement_function)
  715.    return '"' .. newval .. '"'
  716. end
  717.  
  718. local function object_or_array(self, T, etc)
  719.    --
  720.    -- We need to inspect all the keys... if there are any strings, we'll convert to a JSON
  721.    -- object. If there are only numbers, it's a JSON array.
  722.    --
  723.    -- If we'll be converting to a JSON object, we'll want to sort the keys so that the
  724.    -- end result is deterministic.
  725.    --
  726.    local string_keys = { }
  727.    local number_keys = { }
  728.    local number_keys_must_be_strings = false
  729.    local maximum_number_key
  730.  
  731.    for key in pairs(T) do
  732.       if type(key) == 'string' then
  733.          table.insert(string_keys, key)
  734.       elseif type(key) == 'number' then
  735.          table.insert(number_keys, key)
  736.          if key <= 0 or key >= math.huge then
  737.             number_keys_must_be_strings = true
  738.          elseif not maximum_number_key or key > maximum_number_key then
  739.             maximum_number_key = key
  740.          end
  741.       else
  742.          self:onEncodeError("can't encode table with a key of type " .. type(key), etc)
  743.       end
  744.    end
  745.  
  746.    if #string_keys == 0 and not number_keys_must_be_strings then
  747.       --
  748.       -- An empty table, or a numeric-only array
  749.       --
  750.       if #number_keys > 0 then
  751.          return nil, maximum_number_key -- an array
  752.       elseif tostring(T) == "JSON array" then
  753.          return nil
  754.       elseif tostring(T) == "JSON object" then
  755.          return { }
  756.       else
  757.          -- have to guess, so we'll pick array, since empty arrays are likely more common than empty objects
  758.          return nil
  759.       end
  760.    end
  761.  
  762.    table.sort(string_keys)
  763.  
  764.    local map
  765.    if #number_keys > 0 then
  766.       --
  767.       -- If we're here then we have either mixed string/number keys, or numbers inappropriate for a JSON array
  768.       -- It's not ideal, but we'll turn the numbers into strings so that we can at least create a JSON object.
  769.       --
  770.  
  771.       if self.noKeyConversion then
  772.          self:onEncodeError("a table with both numeric and string keys could be an object or array; aborting", etc)
  773.       end
  774.  
  775.       --
  776.       -- Have to make a shallow copy of the source table so we can remap the numeric keys to be strings
  777.       --
  778.       map = { }
  779.       for key, val in pairs(T) do
  780.          map[key] = val
  781.       end
  782.  
  783.       table.sort(number_keys)
  784.  
  785.       --
  786.       -- Throw numeric keys in there as strings
  787.       --
  788.       for _, number_key in ipairs(number_keys) do
  789.          local string_key = tostring(number_key)
  790.          if map[string_key] == nil then
  791.             table.insert(string_keys , string_key)
  792.             map[string_key] = T[number_key]
  793.          else
  794.             self:onEncodeError("conflict converting table with mixed-type keys into a JSON object: key " .. number_key .. " exists both as a string and a number.", etc)
  795.          end
  796.       end
  797.    end
  798.  
  799.    return string_keys, nil, map
  800. end
  801.  
  802. --
  803. -- Encode
  804. --
  805. -- 'options' is nil, or a table with possible keys:
  806. --    pretty            -- if true, return a pretty-printed version
  807. --    indent            -- a string (usually of spaces) used to indent each nested level
  808. --    align_keys        -- if true, align all the keys when formatting a table
  809. --
  810. local encode_value -- must predeclare because it calls itself
  811. function encode_value(self, value, parents, etc, options, indent)
  812.  
  813.    if value == nil then
  814.       return 'null'
  815.  
  816.    elseif type(value) == 'string' then
  817.       return json_string_literal(value)
  818.  
  819.    elseif type(value) == 'number' then
  820.       if value ~= value then
  821.          --
  822.          -- NaN (Not a Number).
  823.          -- JSON has no NaN, so we have to fudge the best we can. This should really be a package option.
  824.          --
  825.          return "null"
  826.       elseif value >= math.huge then
  827.          --
  828.          -- Positive infinity. JSON has no INF, so we have to fudge the best we can. This should
  829.          -- really be a package option. Note: at least with some implementations, positive infinity
  830.          -- is both ">= math.huge" and "<= -math.huge", which makes no sense but that's how it is.
  831.          -- Negative infinity is properly "<= -math.huge". So, we must be sure to check the ">="
  832.          -- case first.
  833.          --
  834.          return "1e+9999"
  835.       elseif value <= -math.huge then
  836.          --
  837.          -- Negative infinity.
  838.          -- JSON has no INF, so we have to fudge the best we can. This should really be a package option.
  839.          --
  840.          return "-1e+9999"
  841.       else
  842.          return tostring(value)
  843.       end
  844.  
  845.    elseif type(value) == 'boolean' then
  846.       return tostring(value)
  847.  
  848.    elseif type(value) ~= 'table' then
  849.       self:onEncodeError("can't convert " .. type(value) .. " to JSON", etc)
  850.  
  851.    else
  852.       --
  853.       -- A table to be converted to either a JSON object or array.
  854.       --
  855.       local T = value
  856.  
  857.       if type(options) ~= 'table' then
  858.          options = {}
  859.       end
  860.       if type(indent) ~= 'string' then
  861.          indent = ""
  862.       end
  863.  
  864.       if parents[T] then
  865.          self:onEncodeError("table " .. tostring(T) .. " is a child of itself", etc)
  866.       else
  867.          parents[T] = true
  868.       end
  869.  
  870.       local result_value
  871.  
  872.       local object_keys, maximum_number_key, map = object_or_array(self, T, etc)
  873.       if maximum_number_key then
  874.          --
  875.          -- An array...
  876.          --
  877.          local ITEMS = { }
  878.          for i = 1, maximum_number_key do
  879.             table.insert(ITEMS, encode_value(self, T[i], parents, etc, options, indent))
  880.          end
  881.  
  882.          if options.pretty then
  883.             result_value = "[ " .. table.concat(ITEMS, ", ") .. " ]"
  884.          else
  885.             result_value = "["  .. table.concat(ITEMS, ",")  .. "]"
  886.          end
  887.  
  888.       elseif object_keys then
  889.          --
  890.          -- An object
  891.          --
  892.          local TT = map or T
  893.  
  894.          if options.pretty then
  895.  
  896.             local KEYS = { }
  897.             local max_key_length = 0
  898.             for _, key in ipairs(object_keys) do
  899.                local encoded = encode_value(self, tostring(key), parents, etc, options, indent)
  900.                if options.align_keys then
  901.                   max_key_length = math.max(max_key_length, #encoded)
  902.                end
  903.                table.insert(KEYS, encoded)
  904.             end
  905.             local key_indent = indent .. tostring(options.indent or "")
  906.             local subtable_indent = key_indent .. string.rep(" ", max_key_length) .. (options.align_keys and "  " or "")
  907.             local FORMAT = "%s%" .. string.format("%d", max_key_length) .. "s: %s"
  908.  
  909.             local COMBINED_PARTS = { }
  910.             for i, key in ipairs(object_keys) do
  911.                local encoded_val = encode_value(self, TT[key], parents, etc, options, subtable_indent)
  912.                table.insert(COMBINED_PARTS, string.format(FORMAT, key_indent, KEYS[i], encoded_val))
  913.             end
  914.             result_value = "{\n" .. table.concat(COMBINED_PARTS, ",\n") .. "\n" .. indent .. "}"
  915.  
  916.          else
  917.  
  918.             local PARTS = { }
  919.             for _, key in ipairs(object_keys) do
  920.                local encoded_val = encode_value(self, TT[key],       parents, etc, options, indent)
  921.                local encoded_key = encode_value(self, tostring(key), parents, etc, options, indent)
  922.                table.insert(PARTS, string.format("%s:%s", encoded_key, encoded_val))
  923.             end
  924.             result_value = "{" .. table.concat(PARTS, ",") .. "}"
  925.  
  926.          end
  927.       else
  928.          --
  929.          -- An empty array/object... we'll treat it as an array, though it should really be an option
  930.          --
  931.          result_value = "[]"
  932.       end
  933.  
  934.       parents[T] = false
  935.       return result_value
  936.    end
  937. end
  938.  
  939.  
  940. function OBJDEF:encode(value, etc, options)
  941.    if type(self) ~= 'table' or self.__index ~= OBJDEF then
  942.       OBJDEF:onEncodeError("JSON:encode must be called in method format", etc)
  943.    end
  944.    return encode_value(self, value, {}, etc, options or nil)
  945. end
  946.  
  947. function OBJDEF:encode_pretty(value, etc, options)
  948.    if type(self) ~= 'table' or self.__index ~= OBJDEF then
  949.       OBJDEF:onEncodeError("JSON:encode_pretty must be called in method format", etc)
  950.    end
  951.    return encode_value(self, value, {}, etc, options or default_pretty_options)
  952. end
  953.  
  954. function OBJDEF.__tostring()
  955.    return "JSON encode/decode package"
  956. end
  957.  
  958. OBJDEF.__index = OBJDEF
  959.  
  960. function OBJDEF:new(args)
  961.    local new = { }
  962.  
  963.    if args then
  964.       for key, val in pairs(args) do
  965.          new[key] = val
  966.       end
  967.    end
  968.  
  969.    return setmetatable(new, OBJDEF)
  970. end
  971.  
  972. return OBJDEF:new()
  973.  
  974. --
  975. -- Version history:
  976. --
  977. --   20141223.14   The encode_pretty() routine produced fine results for small datasets, but isn't really
  978. --                 appropriate for anything large, so with help from Alex Aulbach I've made the encode routines
  979. --                 more flexible, and changed the default encode_pretty() to be more generally useful.
  980. --
  981. --                 Added a third 'options' argument to the encode() and encode_pretty() routines, to control
  982. --                 how the encoding takes place.
  983. --
  984. --                 Updated docs to add assert() call to the loadfile() line, just as good practice so that
  985. --                 if there is a problem loading JSON.lua, the appropriate error message will percolate up.
  986. --
  987. --   20140920.13   Put back (in a way that doesn't cause warnings about unused variables) the author string,
  988. --                 so that the source of the package, and its version number, are visible in compiled copies.
  989. --
  990. --   20140911.12   Minor lua cleanup.
  991. --                 Fixed internal reference to 'JSON.noKeyConversion' to reference 'self' instead of 'JSON'.
  992. --                 (Thanks to SmugMug's David Parry for these.)
  993. --
  994. --   20140418.11   JSON nulls embedded within an array were being ignored, such that
  995. --                     ["1",null,null,null,null,null,"seven"],
  996. --                 would return
  997. --                     {1,"seven"}
  998. --                 It's now fixed to properly return
  999. --                     {1, nil, nil, nil, nil, nil, "seven"}
  1000. --                 Thanks to "haddock" for catching the error.
  1001. --
  1002. --   20140116.10   The user's JSON.assert() wasn't always being used. Thanks to "blue" for the heads up.
  1003. --
  1004. --   20131118.9    Update for Lua 5.3... it seems that tostring(2/1) produces "2.0" instead of "2",
  1005. --                 and this caused some problems.
  1006. --
  1007. --   20131031.8    Unified the code for encode() and encode_pretty(); they had been stupidly separate,
  1008. --                 and had of course diverged (encode_pretty didn't get the fixes that encode got, so
  1009. --                 sometimes produced incorrect results; thanks to Mattie for the heads up).
  1010. --
  1011. --                 Handle encoding tables with non-positive numeric keys (unlikely, but possible).
  1012. --
  1013. --                 If a table has both numeric and string keys, or its numeric keys are inappropriate
  1014. --                 (such as being non-positive or infinite), the numeric keys are turned into
  1015. --                 string keys appropriate for a JSON object. So, as before,
  1016. --                         JSON:encode({ "one", "two", "three" })
  1017. --                 produces the array
  1018. --                         ["one","two","three"]
  1019. --                 but now something with mixed key types like
  1020. --                         JSON:encode({ "one", "two", "three", SOMESTRING = "some string" }))
  1021. --                 instead of throwing an error produces an object:
  1022. --                         {"1":"one","2":"two","3":"three","SOMESTRING":"some string"}
  1023. --
  1024. --                 To maintain the prior throw-an-error semantics, set
  1025. --                      JSON.noKeyConversion = true
  1026. --
  1027. --   20131004.7    Release under a Creative Commons CC-BY license, which I should have done from day one, sorry.
  1028. --
  1029. --   20130120.6    Comment update: added a link to the specific page on my blog where this code can
  1030. --                 be found, so that folks who come across the code outside of my blog can find updates
  1031. --                 more easily.
  1032. --
  1033. --   20111207.5    Added support for the 'etc' arguments, for better error reporting.
  1034. --
  1035. --   20110731.4    More feedback from David Kolf on how to make the tests for Nan/Infinity system independent.
  1036. --
  1037. --   20110730.3    Incorporated feedback from David Kolf at http://lua-users.org/wiki/JsonModules:
  1038. --
  1039. --                   * When encoding lua for JSON, Sparse numeric arrays are now handled by
  1040. --                     spitting out full arrays, such that
  1041. --                        JSON:encode({"one", "two", [10] = "ten"})
  1042. --                     returns
  1043. --                        ["one","two",null,null,null,null,null,null,null,"ten"]
  1044. --
  1045. --                     In 20100810.2 and earlier, only up to the first non-null value would have been retained.
  1046. --
  1047. --                   * When encoding lua for JSON, numeric value NaN gets spit out as null, and infinity as "1+e9999".
  1048. --                     Version 20100810.2 and earlier created invalid JSON in both cases.
  1049. --
  1050. --                   * Unicode surrogate pairs are now detected when decoding JSON.
  1051. --
  1052. --   20100810.2    added some checking to ensure that an invalid Unicode character couldn't leak in to the UTF-8 encoding
  1053. --
  1054. --   20100731.1    initial public release
  1055. --
  1056. ]])()
  1057.  
  1058. --My Code
  1059. local official = "http://backspace.cf/api/v3/"
  1060. local url = official
  1061. local jwt = ""
  1062.  
  1063. local function getHeaders()
  1064.   local h = {}
  1065.   if jwt ~= "" then
  1066.     h.Authorization = "Bearer "..jwt
  1067.   end
  1068.   h["Content-Type"] = "application/json"
  1069.   return h
  1070. end
  1071.  
  1072. function setUrl(new)
  1073.   url = new
  1074. end
  1075.  
  1076. function resetUrl()
  1077.   url = official
  1078. end
  1079.  
  1080. function hasJWT()
  1081.   return jwt ~= ""
  1082. end
  1083.  
  1084. function getJWT()
  1085.   return jwt
  1086. end
  1087.  
  1088. function setJWT(new)
  1089.   jwt = new
  1090. end
  1091.  
  1092. local function request(url,data,headers,success,err)
  1093.   http.request(url,data,headers)
  1094.   local requesting = true
  1095.   local failed = false
  1096.   while requesting do
  1097.     local event,url,source = os.pullEvent()
  1098.     if(event == "http_success") then
  1099.       success(JSON:decode(source.readAll()))
  1100.       source.close()
  1101.       requesting = false
  1102.     elseif(event == "http_failure") then
  1103.       err(JSON:decode(source.readAll()))
  1104.       source.close()
  1105.       requesting = false
  1106.     end
  1107.   end
  1108. end
  1109.  
  1110. function send(call,data,success,err)
  1111.   request(url..call,JSON:encode(data),getHeaders(),success,er)
  1112. end
  1113.  
  1114. --[[
  1115. function login(name,password)
  1116.  
  1117. end
  1118.  
  1119. function register(name,password)
  1120.  
  1121. end]]--
  1122.  
  1123. function logout()
  1124.   setJWT("")
  1125. end
Advertisement
Add Comment
Please, Sign In to add comment