Advertisement
PortalAtlas

json.lua

Jun 25th, 2019
174
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 26.42 KB | None | 0 0
  1. -- -*- coding: utf-8 -*-
  2. --
  3. -- Copyright 2010-2012 Jeffrey Friedl
  4. -- http://regex.info/blog/
  5. --
  6. local VERSION = 20111207.5  -- version history at end of file
  7. local OBJDEF = { VERSION = VERSION }
  8.  
  9. --
  10. -- Simple JSON encoding and decoding in pure Lua.
  11. -- http://www.json.org/
  12. --
  13. --
  14. --   JSON = (loadfile "JSON.lua")() -- one-time load of the routines
  15. --
  16. --   local lua_value = JSON:decode(raw_json_text)
  17. --
  18. --   local raw_json_text    = JSON:encode(lua_table_or_value)
  19. --   local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability
  20. --
  21. --
  22. -- DECODING
  23. --
  24. --   JSON = (loadfile "JSON.lua")() -- one-time load of the routines
  25. --
  26. --   local lua_value = JSON:decode(raw_json_text)
  27. --
  28. --   If the JSON text is for an object or an array, e.g.
  29. --     { "what": "books", "count": 3 }
  30. --   or
  31. --     [ "Larry", "Curly", "Moe" ]
  32. --
  33. --   the result is a Lua table, e.g.
  34. --     { what = "books", count = 3 }
  35. --   or
  36. --     { "Larry", "Curly", "Moe" }
  37. --
  38. --
  39. --   The encode and decode routines accept an optional second argument, "etc", which is not used
  40. --   during encoding or decoding, but upon error is passed along to error handlers. It can be of any
  41. --   type (including nil).
  42. --
  43. --   With most errors during decoding, this code calls
  44. --
  45. --      JSON:onDecodeError(message, text, location, etc)
  46. --
  47. --   with a message about the error, and if known, the JSON text being parsed and the byte count
  48. --   where the problem was discovered. You can replace the default JSON:onDecodeError() with your
  49. --   own function.
  50. --
  51. --   The default onDecodeError() merely augments the message with data about the text and the
  52. --   location if known (and if a second 'etc' argument had been provided to decode(), its value is
  53. --   tacked onto the message as well), and then calls JSON.assert(), which itself defaults to Lua's
  54. --   built-in assert(), and can also be overridden.
  55. --
  56. --   For example, in an Adobe Lightroom plugin, you might use something like
  57. --
  58. --          function JSON:onDecodeError(message, text, location, etc)
  59. --             LrErrors.throwUserError("Internal Error: invalid JSON data")
  60. --          end
  61. --
  62. --   or even just
  63. --
  64. --          function JSON.assert(message)
  65. --             LrErrors.throwUserError("Internal Error: " .. message)
  66. --          end
  67. --
  68. --   If JSON:decode() is passed a nil, this is called instead:
  69. --
  70. --      JSON:onDecodeOfNilError(message, nil, nil, etc)
  71. --
  72. --   and if JSON:decode() is passed HTML instead of JSON, this is called:
  73. --
  74. --      JSON:onDecodeOfHTMLError(message, text, nil, etc)
  75. --
  76. --   The use of the fourth 'etc' argument allows stronger coordination between decoding and error
  77. --   reporting, especially when you provide your own error-handling routines. Continuing with the
  78. --   the Adobe Lightroom plugin example:
  79. --
  80. --          function JSON:onDecodeError(message, text, location, etc)
  81. --             local note = "Internal Error: invalid JSON data"
  82. --             if type(etc) = 'table' and etc.photo then
  83. --                note = note .. " while processing for " .. etc.photo:getFormattedMetadata('fileName')
  84. --             end
  85. --             LrErrors.throwUserError(note)
  86. --          end
  87. --
  88. --            :
  89. --            :
  90. --
  91. --          for i, photo in ipairs(photosToProcess) do
  92. --               :            
  93. --               :            
  94. --               local data = JSON:decode(someJsonText, { photo = photo })
  95. --               :            
  96. --               :            
  97. --          end
  98. --
  99. --
  100. --
  101. --
  102.  
  103. -- DECODING AND STRICT TYPES
  104. --
  105. --   Because both JSON objects and JSON arrays are converted to Lua tables, it's not normally
  106. --   possible to tell which a Lua table came from, or guarantee decode-encode round-trip
  107. --   equivalency.
  108. --
  109. --   However, if you enable strictTypes, e.g.
  110. --
  111. --      JSON = (loadfile "JSON.lua")() --load the routines
  112. --      JSON.strictTypes = true
  113. --
  114. --   then the Lua table resulting from the decoding of a JSON object or JSON array is marked via Lua
  115. --   metatable, so that when re-encoded with JSON:encode() it ends up as the appropriate JSON type.
  116. --
  117. --   (This is not the default because other routines may not work well with tables that have a
  118. --   metatable set, for example, Lightroom API calls.)
  119. --
  120. --
  121. -- ENCODING
  122. --
  123. --   JSON = (loadfile "JSON.lua")() -- one-time load of the routines
  124. --
  125. --   local raw_json_text    = JSON:encode(lua_table_or_value)
  126. --   local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability
  127.  
  128. --   On error during encoding, this code calls:
  129. --
  130. --    JSON:onEncodeError(message, etc)
  131. --
  132. --   which you can override in your local JSON object.
  133. --
  134. --
  135. -- SUMMARY OF METHODS YOU CAN OVERRIDE IN YOUR LOCAL LUA JSON OBJECT
  136. --
  137. --    assert
  138. --    onDecodeError
  139. --    onDecodeOfNilError
  140. --    onDecodeOfHTMLError
  141. --    onEncodeError
  142. --
  143. --  If you want to create a separate Lua JSON object with its own error handlers,
  144. --  you can reload JSON.lua or use the :new() method.
  145. --
  146. ---------------------------------------------------------------------------
  147.  
  148.  
  149. local author = "-[ JSON.lua package by Jeffrey Friedl (http://regex.info/blog/lua/json), version " .. tostring(VERSION) .. " ]-"
  150. local isArray  = { __tostring = function() return "JSON array"  end }    isArray.__index  = isArray
  151. local isObject = { __tostring = function() return "JSON object" end }    isObject.__index = isObject
  152.  
  153.  
  154. function OBJDEF:newArray(tbl)
  155.    return setmetatable(tbl or {}, isArray)
  156. end
  157.  
  158. function OBJDEF:newObject(tbl)
  159.    return setmetatable(tbl or {}, isObject)
  160. end
  161.  
  162. local function unicode_codepoint_as_utf8(codepoint)
  163.    --
  164.    -- codepoint is a number
  165.    --
  166.    if codepoint <= 127 then
  167.       return string.char(codepoint)
  168.  
  169.    elseif codepoint <= 2047 then
  170.       --
  171.       -- 110yyyxx 10xxxxxx         <-- useful notation from http://en.wikipedia.org/wiki/Utf8
  172.       --
  173.       local highpart = math.floor(codepoint / 0x40)
  174.       local lowpart  = codepoint - (0x40 * highpart)
  175.       return string.char(0xC0 + highpart,
  176.                          0x80 + lowpart)
  177.  
  178.    elseif codepoint <= 65535 then
  179.       --
  180.       -- 1110yyyy 10yyyyxx 10xxxxxx
  181.       --
  182.       local highpart  = math.floor(codepoint / 0x1000)
  183.       local remainder = codepoint - 0x1000 * highpart
  184.       local midpart   = math.floor(remainder / 0x40)
  185.       local lowpart   = remainder - 0x40 * midpart
  186.  
  187.       highpart = 0xE0 + highpart
  188.       midpart  = 0x80 + midpart
  189.       lowpart  = 0x80 + lowpart
  190.  
  191.       --
  192.       -- Check for an invalid character (thanks Andy R. at Adobe).
  193.       -- See table 3.7, page 93, in http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf#G28070
  194.       --
  195.       if ( highpart == 0xE0 and midpart < 0xA0 ) or
  196.          ( highpart == 0xED and midpart > 0x9F ) or
  197.          ( highpart == 0xF0 and midpart < 0x90 ) or
  198.          ( highpart == 0xF4 and midpart > 0x8F )
  199.       then
  200.          return "?"
  201.       else
  202.          return string.char(highpart,
  203.                             midpart,
  204.                             lowpart)
  205.       end
  206.  
  207.    else
  208.       --
  209.       -- 11110zzz 10zzyyyy 10yyyyxx 10xxxxxx
  210.       --
  211.       local highpart  = math.floor(codepoint / 0x40000)
  212.       local remainder = codepoint - 0x40000 * highpart
  213.       local midA      = math.floor(remainder / 0x1000)
  214.       remainder       = remainder - 0x1000 * midA
  215.       local midB      = math.floor(remainder / 0x40)
  216.       local lowpart   = remainder - 0x40 * midB
  217.  
  218.       return string.char(0xF0 + highpart,
  219.                          0x80 + midA,
  220.                          0x80 + midB,
  221.                          0x80 + lowpart)
  222.    end
  223. end
  224.  
  225. function OBJDEF:onDecodeError(message, text, location, etc)
  226.    if text then
  227.       if location then
  228.          message = string.format("%s at char %d of: %s", message, location, text)
  229.       else
  230.          message = string.format("%s: %s", message, text)
  231.       end
  232.    end
  233.    if etc ~= nil then
  234.       message = message .. " (" .. OBJDEF:encode(etc) .. ")"
  235.    end
  236.  
  237.    if self.assert then
  238.       self.assert(false, message)
  239.    else
  240.       assert(false, message)
  241.    end
  242. end
  243.  
  244. OBJDEF.onDecodeOfNilError  = OBJDEF.onDecodeError
  245. OBJDEF.onDecodeOfHTMLError = OBJDEF.onDecodeError
  246.  
  247. function OBJDEF:onEncodeError(message, etc)
  248.    if etc ~= nil then
  249.       message = message .. " (" .. OBJDEF:encode(etc) .. ")"
  250.    end
  251.  
  252.    if self.assert then
  253.       self.assert(false, message)
  254.    else
  255.       assert(false, message)
  256.    end
  257. end
  258.  
  259. local function grok_number(self, text, start, etc)
  260.    --
  261.    -- Grab the integer part
  262.    --
  263.    local integer_part = text:match('^-?[1-9]%d*', start)
  264.                      or text:match("^-?0",        start)
  265.  
  266.    if not integer_part then
  267.       self:onDecodeError("expected number", text, start, etc)
  268.    end
  269.  
  270.    local i = start + integer_part:len()
  271.  
  272.    --
  273.    -- Grab an optional decimal part
  274.    --
  275.    local decimal_part = text:match('^%.%d+', i) or ""
  276.  
  277.    i = i + decimal_part:len()
  278.  
  279.    --
  280.    -- Grab an optional exponential part
  281.    --
  282.    local exponent_part = text:match('^[eE][-+]?%d+', i) or ""
  283.  
  284.    i = i + exponent_part:len()
  285.  
  286.    local full_number_text = integer_part .. decimal_part .. exponent_part
  287.    local as_number = tonumber(full_number_text)
  288.  
  289.    if not as_number then
  290.       self:onDecodeError("bad number", text, start, etc)
  291.    end
  292.  
  293.    return as_number, i
  294. end
  295.  
  296.  
  297. local function grok_string(self, text, start, etc)
  298.  
  299.    if text:sub(start,start) ~= '"' then
  300.       self:onDecodeError("expected string's opening quote", text, start, etc)
  301.    end
  302.  
  303.    local i = start + 1 -- +1 to bypass the initial quote
  304.    local text_len = text:len()
  305.    local VALUE = ""
  306.    while i <= text_len do
  307.       local c = text:sub(i,i)
  308.       if c == '"' then
  309.          return VALUE, i + 1
  310.       end
  311.       if c ~= '\\' then
  312.          VALUE = VALUE .. c
  313.          i = i + 1
  314.       elseif text:match('^\\b', i) then
  315.          VALUE = VALUE .. "\b"
  316.          i = i + 2
  317.       elseif text:match('^\\f', i) then
  318.          VALUE = VALUE .. "\f"
  319.          i = i + 2
  320.       elseif text:match('^\\n', i) then
  321.          VALUE = VALUE .. "\n"
  322.          i = i + 2
  323.       elseif text:match('^\\r', i) then
  324.          VALUE = VALUE .. "\r"
  325.          i = i + 2
  326.       elseif text:match('^\\t', i) then
  327.          VALUE = VALUE .. "\t"
  328.          i = i + 2
  329.       else
  330.          local hex = text:match('^\\u([0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i)
  331.          if hex then
  332.             i = i + 6 -- bypass what we just read
  333.  
  334.             -- We have a Unicode codepoint. It could be standalone, or if in the proper range and
  335.             -- followed by another in a specific range, it'll be a two-code surrogate pair.
  336.             local codepoint = tonumber(hex, 16)
  337.             if codepoint >= 0xD800 and codepoint <= 0xDBFF then
  338.                -- it's a hi surrogate... see whether we have a following low
  339.                local lo_surrogate = text:match('^\\u([dD][cdefCDEF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i)
  340.                if lo_surrogate then
  341.                   i = i + 6 -- bypass the low surrogate we just read
  342.                   codepoint = 0x2400 + (codepoint - 0xD800) * 0x400 + tonumber(lo_surrogate, 16)
  343.                else
  344.                   -- not a proper low, so we'll just leave the first codepoint as is and spit it out.
  345.                end
  346.             end
  347.             VALUE = VALUE .. unicode_codepoint_as_utf8(codepoint)
  348.  
  349.          else
  350.  
  351.             -- just pass through what's escaped
  352.             VALUE = VALUE .. text:match('^\\(.)', i)
  353.             i = i + 2
  354.          end
  355.       end
  356.    end
  357.  
  358.    self:onDecodeError("unclosed string", text, start, etc)
  359. end
  360.  
  361. local function skip_whitespace(text, start)
  362.  
  363.    local match_start, match_end = text:find("^[ \n\r\t]+", start) -- [http://www.ietf.org/rfc/rfc4627.txt] Section 2
  364.    if match_end then
  365.       return match_end + 1
  366.    else
  367.       return start
  368.    end
  369. end
  370.  
  371. local grok_one -- assigned later
  372.  
  373. local function grok_object(self, text, start, etc)
  374.    if not text:sub(start,start) == '{' then
  375.       self:onDecodeError("expected '{'", text, start, etc)
  376.    end
  377.  
  378.    local i = skip_whitespace(text, start + 1) -- +1 to skip the '{'
  379.  
  380.    local VALUE = self.strictTypes and self:newObject { } or { }
  381.  
  382.    if text:sub(i,i) == '}' then
  383.       return VALUE, i + 1
  384.    end
  385.    local text_len = text:len()
  386.    while i <= text_len do
  387.       local key, new_i = grok_string(self, text, i, etc)
  388.  
  389.       i = skip_whitespace(text, new_i)
  390.  
  391.       if text:sub(i, i) ~= ':' then
  392.          self:onDecodeError("expected colon", text, i, etc)
  393.       end
  394.  
  395.       i = skip_whitespace(text, i + 1)
  396.  
  397.       local val, new_i = grok_one(self, text, i)
  398.  
  399.       VALUE[key] = val
  400.  
  401.       --
  402.       -- Expect now either '}' to end things, or a ',' to allow us to continue.
  403.       --
  404.       i = skip_whitespace(text, new_i)
  405.  
  406.       local c = text:sub(i,i)
  407.  
  408.       if c == '}' then
  409.          return VALUE, i + 1
  410.       end
  411.  
  412.       if text:sub(i, i) ~= ',' then
  413.          self:onDecodeError("expected comma or '}'", text, i, etc)
  414.       end
  415.  
  416.       i = skip_whitespace(text, i + 1)
  417.    end
  418.  
  419.    self:onDecodeError("unclosed '{'", text, start, etc)
  420. end
  421.  
  422. local function grok_array(self, text, start, etc)
  423.    if not text:sub(start,start) == '[' then
  424.       self:onDecodeError("expected '['", text, start, etc)
  425.    end
  426.  
  427.    local i = skip_whitespace(text, start + 1) -- +1 to skip the '['
  428.    local VALUE = self.strictTypes and self:newArray { } or { }
  429.    if text:sub(i,i) == ']' then
  430.       return VALUE, i + 1
  431.    end
  432.  
  433.    local text_len = text:len()
  434.    while i <= text_len do
  435.       local val, new_i = grok_one(self, text, i)
  436.  
  437.       table.insert(VALUE, val)
  438.  
  439.       i = skip_whitespace(text, new_i)
  440.  
  441.       --
  442.       -- Expect now either ']' to end things, or a ',' to allow us to continue.
  443.       --
  444.       local c = text:sub(i,i)
  445.       if c == ']' then
  446.          return VALUE, i + 1
  447.       end
  448.       if text:sub(i, i) ~= ',' then
  449.          self:onDecodeError("expected comma or '['", text, i, etc)
  450.       end
  451.       i = skip_whitespace(text, i + 1)
  452.    end
  453.    self:onDecodeError("unclosed '['", text, start, etc)
  454. end
  455.  
  456.  
  457. grok_one = function(self, text, start, etc)
  458.    -- Skip any whitespace
  459.    start = skip_whitespace(text, start)
  460.  
  461.    if start > text:len() then
  462.       self:onDecodeError("unexpected end of string", text, nil, etc)
  463.    end
  464.  
  465.    if text:find('^"', start) then
  466.       return grok_string(self, text, start, etc)
  467.  
  468.    elseif text:find('^[-0123456789 ]', start) then
  469.       return grok_number(self, text, start, etc)
  470.  
  471.    elseif text:find('^%{', start) then
  472.       return grok_object(self, text, start, etc)
  473.  
  474.    elseif text:find('^%[', start) then
  475.       return grok_array(self, text, start, etc)
  476.  
  477.    elseif text:find('^true', start) then
  478.       return true, start + 4
  479.  
  480.    elseif text:find('^false', start) then
  481.       return false, start + 5
  482.  
  483.    elseif text:find('^null', start) then
  484.       return nil, start + 4
  485.  
  486.    else
  487.       self:onDecodeError("can't parse JSON", text, start, etc)
  488.    end
  489. end
  490.  
  491. function OBJDEF:decode(text, etc)
  492.    if type(self) ~= 'table' or self.__index ~= OBJDEF then
  493.       OBJDEF:onDecodeError("JSON:decode must be called in method format", nil, nil, etc)
  494.    end
  495.  
  496.    if text == nil then
  497.       self:onDecodeOfNilError(string.format("nil passed to JSON:decode()"), nil, nil, etc)
  498.    elseif type(text) ~= 'string' then
  499.       self:onDecodeError(string.format("expected string argument to JSON:decode(), got %s", type(text)), nil, nil, etc)
  500.    end
  501.  
  502.    if text:match('^%s*$') then
  503.       return nil
  504.    end
  505.  
  506.    if text:match('^%s*<') then
  507.       -- Can't be JSON... we'll assume it's HTML
  508.       self:onDecodeOfHTMLError(string.format("html passed to JSON:decode()"), text, nil, etc)
  509.    end
  510.  
  511.    --
  512.    -- Ensure that it's not UTF-32 or UTF-16.
  513.    -- Those are perfectly valid encodings for JSON (as per RFC 4627 section 3),
  514.    -- but this package can't handle them.
  515.    --
  516.    if text:sub(1,1):byte() == 0 or (text:len() >= 2 and text:sub(2,2):byte() == 0) then
  517.       self:onDecodeError("JSON package groks only UTF-8, sorry", text, nil, etc)
  518.    end
  519.  
  520.    local success, value = pcall(grok_one, self, text, 1, etc)
  521.    if success then
  522.       return value
  523.    else
  524.       -- should never get here... JSON parse errors should have been caught earlier
  525.       assert(false, value)
  526.       return nil
  527.    end
  528. end
  529.  
  530. local function backslash_replacement_function(c)
  531.    if c == "\n" then
  532.       return "\\n"
  533.    elseif c == "\r" then
  534.       return "\\r"
  535.    elseif c == "\t" then
  536.       return "\\t"
  537.    elseif c == "\b" then
  538.       return "\\b"
  539.    elseif c == "\f" then
  540.       return "\\f"
  541.    elseif c == '"' then
  542.       return '\\"'
  543.    elseif c == '\\' then
  544.       return '\\\\'
  545.    else
  546.       return string.format("\\u%04x", c:byte())
  547.    end
  548. end
  549.  
  550. local chars_to_be_escaped_in_JSON_string
  551.    = '['
  552.    ..    '"'    -- class sub-pattern to match a double quote
  553.    ..    '%\\'  -- class sub-pattern to match a backslash
  554.    ..    '%z'   -- class sub-pattern to match a null
  555.    ..    '\001' .. '-' .. '\031' -- class sub-pattern to match control characters
  556.    .. ']'
  557.  
  558. local function json_string_literal(value)
  559.    local newval = value:gsub(chars_to_be_escaped_in_JSON_string, backslash_replacement_function)
  560.    return '"' .. newval .. '"'
  561. end
  562.  
  563. local function object_or_array(self, T, etc)
  564.    --
  565.    -- We need to inspect all the keys... if there are any strings, we'll convert to a JSON
  566.    -- object. If there are only numbers, it's a JSON array.
  567.    --
  568.    -- If we'll be converting to a JSON object, we'll want to sort the keys so that the
  569.    -- end result is deterministic.
  570.    --
  571.    local string_keys = { }
  572.    local seen_number_key = false
  573.    local maximum_number_key
  574.  
  575.    for key in pairs(T) do
  576.       if type(key) == 'number' then
  577.          seen_number_key = true
  578.          if not maximum_number_key or maximum_number_key < key then
  579.             maximum_number_key = key
  580.          end
  581.       elseif type(key) == 'string' then
  582.          table.insert(string_keys, key)
  583.       else
  584.          self:onEncodeError("can't encode table with a key of type " .. type(key), etc)
  585.       end
  586.    end
  587.  
  588.    if seen_number_key and #string_keys > 0 then
  589.       --
  590.       -- Mixed key types... don't know what to do, so bail
  591.       --
  592.       self:onEncodeError("a table with both numeric and string keys could be an object or array; aborting", etc)
  593.  
  594.    elseif #string_keys == 0  then
  595.       --
  596.       -- An array
  597.       --
  598.       if seen_number_key then
  599.          return nil, maximum_number_key -- an array
  600.       else
  601.          --
  602.          -- An empty table...
  603.          --
  604.          if tostring(T) == "JSON array" then
  605.             return nil
  606.          elseif tostring(T) == "JSON object" then
  607.             return { }
  608.          else
  609.             -- have to guess, so we'll pick array, since empty arrays are likely more common than empty objects
  610.             return nil
  611.          end
  612.       end
  613.    else
  614.       --
  615.       -- An object, so return a list of keys
  616.       --
  617.       table.sort(string_keys)
  618.       return string_keys
  619.    end
  620. end
  621.  
  622. --
  623. -- Encode
  624. --
  625. local encode_value -- must predeclare because it calls itself
  626. function encode_value(self, value, parents, etc)
  627.  
  628.  
  629.    if value == nil then
  630.       return 'null'
  631.    end
  632.  
  633.    if type(value) == 'string' then
  634.       return json_string_literal(value)
  635.    elseif type(value) == 'number' then
  636.       if value ~= value then
  637.          --
  638.          -- NaN (Not a Number).
  639.          -- JSON has no NaN, so we have to fudge the best we can. This should really be a package option.
  640.          --
  641.          return "null"
  642.       elseif value >= math.huge then
  643.          --
  644.          -- Positive infinity. JSON has no INF, so we have to fudge the best we can. This should
  645.          -- really be a package option. Note: at least with some implementations, positive infinity
  646.          -- is both ">= math.huge" and "<= -math.huge", which makes no sense but that's how it is.
  647.          -- Negative infinity is properly "<= -math.huge". So, we must be sure to check the ">="
  648.          -- case first.
  649.          --
  650.          return "1e+9999"
  651.       elseif value <= -math.huge then
  652.          --
  653.          -- Negative infinity.
  654.          -- JSON has no INF, so we have to fudge the best we can. This should really be a package option.
  655.          --
  656.          return "-1e+9999"
  657.       else
  658.          return tostring(value)
  659.       end
  660.    elseif type(value) == 'boolean' then
  661.       return tostring(value)
  662.  
  663.    elseif type(value) ~= 'table' then
  664.       self:onEncodeError("can't convert " .. type(value) .. " to JSON", etc)
  665.  
  666.    else
  667.       --
  668.       -- A table to be converted to either a JSON object or array.
  669.       --
  670.       local T = value
  671.  
  672.       if parents[T] then
  673.          self:onEncodeError("table " .. tostring(T) .. " is a child of itself", etc)
  674.       else
  675.          parents[T] = true
  676.       end
  677.  
  678.       local result_value
  679.  
  680.       local object_keys, maximum_number_key = object_or_array(self, T, etc)
  681.       if maximum_number_key then
  682.          --
  683.          -- An array...
  684.          --
  685.          local ITEMS = { }
  686.          for i = 1, maximum_number_key do
  687.             table.insert(ITEMS, encode_value(self, T[i], parents, etc))
  688.          end
  689.  
  690.          result_value = "[" .. table.concat(ITEMS, ",") .. "]"
  691.       elseif object_keys then
  692.          --
  693.          -- An object
  694.          --
  695.  
  696.          --
  697.          -- We'll always sort the keys, so that comparisons can be made on
  698.          -- the results, etc. The actual order is not particularly
  699.          -- important (e.g. it doesn't matter what character set we sort
  700.          -- as); it's only important that it be deterministic... the same
  701.          -- every time.
  702.          --
  703.          local PARTS = { }
  704.          for _, key in ipairs(object_keys) do
  705.             local encoded_key = encode_value(self, tostring(key), parents, etc)
  706.             local encoded_val = encode_value(self, T[key],        parents, etc)
  707.             table.insert(PARTS, string.format("%s:%s", encoded_key, encoded_val))
  708.          end
  709.          result_value = "{" .. table.concat(PARTS, ",") .. "}"
  710.       else
  711.          --
  712.          -- An empty array/object... we'll treat it as an array, though it should really be an option
  713.          --
  714.          result_value = "[]"
  715.       end
  716.  
  717.       parents[T] = false
  718.       return result_value
  719.    end
  720. end
  721.  
  722. local encode_pretty_value -- must predeclare because it calls itself
  723. function encode_pretty_value(self, value, parents, indent, etc)
  724.  
  725.    if type(value) == 'string' then
  726.       return json_string_literal(value)
  727.  
  728.    elseif type(value) == 'number' then
  729.       return tostring(value)
  730.  
  731.    elseif type(value) == 'boolean' then
  732.       return tostring(value)
  733.  
  734.    elseif type(value) == 'nil' then
  735.       return 'null'
  736.  
  737.    elseif type(value) ~= 'table' then
  738.       self:onEncodeError("can't convert " .. type(value) .. " to JSON", etc)
  739.  
  740.    else
  741.       --
  742.       -- A table to be converted to either a JSON object or array.
  743.       --
  744.       local T = value
  745.  
  746.       if parents[T] then
  747.          self:onEncodeError("table " .. tostring(T) .. " is a child of itself", etc)
  748.       end
  749.       parents[T] = true
  750.  
  751.       local result_value
  752.  
  753.       local object_keys = object_or_array(self, T, etc)
  754.       if not object_keys then
  755.          --
  756.          -- An array...
  757.          --
  758.          local ITEMS = { }
  759.          for i = 1, #T do
  760.             table.insert(ITEMS, encode_pretty_value(self, T[i], parents, indent, etc))
  761.          end
  762.  
  763.          result_value = "[ " .. table.concat(ITEMS, ", ") .. " ]"
  764.  
  765.       else
  766.  
  767.          --
  768.          -- An object -- can keys be numbers?
  769.          --
  770.  
  771.          local KEYS = { }
  772.          local max_key_length = 0
  773.          for _, key in ipairs(object_keys) do
  774.             local encoded = encode_pretty_value(self, tostring(key), parents, "", etc)
  775.             max_key_length = math.max(max_key_length, #encoded)
  776.             table.insert(KEYS, encoded)
  777.          end
  778.          local key_indent = indent .. "    "
  779.          local subtable_indent = indent .. string.rep(" ", max_key_length + 2 + 4)
  780.          local FORMAT = "%s%" .. tostring(max_key_length) .. "s: %s"
  781.  
  782.          local COMBINED_PARTS = { }
  783.          for i, key in ipairs(object_keys) do
  784.             local encoded_val = encode_pretty_value(self, T[key], parents, subtable_indent, etc)
  785.             table.insert(COMBINED_PARTS, string.format(FORMAT, key_indent, KEYS[i], encoded_val))
  786.          end
  787.          result_value = "{\n" .. table.concat(COMBINED_PARTS, ",\n") .. "\n" .. indent .. "}"
  788.       end
  789.  
  790.       parents[T] = false
  791.       return result_value
  792.    end
  793. end
  794.  
  795. function OBJDEF:encode(value, etc)
  796.    if type(self) ~= 'table' or self.__index ~= OBJDEF then
  797.       OBJDEF:onEncodeError("JSON:encode must be called in method format", etc)
  798.    end
  799.  
  800.    local parents = {}
  801.    return encode_value(self, value, parents, etc)
  802. end
  803.  
  804. function OBJDEF:encode_pretty(value, etc)
  805.    local parents = {}
  806.    local subtable_indent = ""
  807.    return encode_pretty_value(self, value, parents, subtable_indent, etc)
  808. end
  809.  
  810. function OBJDEF.__tostring()
  811.    return "JSON encode/decode package"
  812. end
  813.  
  814. OBJDEF.__index = OBJDEF
  815.  
  816. function OBJDEF:new(args)
  817.    local new = { }
  818.  
  819.    if args then
  820.       for key, val in pairs(args) do
  821.          new[key] = val
  822.       end
  823.    end
  824.  
  825.    return setmetatable(new, OBJDEF)
  826. end
  827.  
  828. return OBJDEF:new()
  829.  
  830. --
  831. -- Version history:
  832. --
  833. --   20111207.5    Added support for the 'etc' arguments, for better error reporting.
  834. --
  835. --   20110731.4    More feedback from David Kolf on how to make the tests for Nan/Infinity system independent.
  836. --
  837. --   20110730.3    Incorporated feedback from David Kolf at http://lua-users.org/wiki/JsonModules:
  838. --
  839. --                   * When encoding lua for JSON, Sparse numeric arrays are now handled by
  840. --                     spitting out full arrays, such that
  841. --                        JSON:encode({"one", "two", [10] = "ten"})
  842. --                     returns
  843. --                        ["one","two",null,null,null,null,null,null,null,"ten"]
  844. --
  845. --                     In 20100810.2 and earlier, only up to the first non-null value would have been retained.
  846. --
  847. --                   * When encoding lua for JSON, numeric value NaN gets spit out as null, and infinity as "1+e9999".
  848. --                     Version 20100810.2 and earlier created invalid JSON in both cases.
  849. --
  850. --                   * Unicode surrogate pairs are now detected when decoding JSON.
  851. --
  852. --   20100810.2    added some checking to ensure that an invalid Unicode character couldn't leak in to the UTF-8 encoding
  853. --
  854. --   20100731.1    initial public release
  855. --
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement