Module:Json: Difference between revisions

16,815 bytes added ,  29 August 2022
no edit summary
No edit summary
No edit summary
 
Line 1: Line 1:
-- -*- coding: utf-8 -*-
--
--
-- json.lua
-- Copyright 2010-2013 Jeffrey Friedl
-- http://regex.info/blog/
--
--
-- Copyright (c) 2020 rxi
-- Latest copy: http://regex.info/blog/lua/json
--
--
-- Permission is hereby granted, free of charge, to any person obtaining a copy of
local VERSION = 20130120.6  -- version history at end of file
-- this software and associated documentation files (the "Software"), to deal in
local OBJDEF = { VERSION = VERSION }
-- the Software without restriction, including without limitation the rights to
 
-- use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
--
-- of the Software, and to permit persons to whom the Software is furnished to do
-- Simple JSON encoding and decoding in pure Lua.
-- so, subject to the following conditions:
-- http://www.json.org/
--
--
--  JSON = (loadfile "JSON.lua")() -- one-time load of the routines
--
--  local lua_value = JSON:decode(raw_json_text)
--
--  local raw_json_text    = JSON:encode(lua_table_or_value)
--  local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability
--
--
-- DECODING
--
--  JSON = (loadfile "JSON.lua")() -- one-time load of the routines
--
--  local lua_value = JSON:decode(raw_json_text)
--
--  If the JSON text is for an object or an array, e.g.
--    { "what": "books", "count": 3 }
--  or
--    [ "Larry", "Curly", "Moe" ]
--
--  the result is a Lua table, e.g.
--    { what = "books", count = 3 }
--  or
--    { "Larry", "Curly", "Moe" }
--
--
--  The encode and decode routines accept an optional second argument, "etc", which is not used
--  during encoding or decoding, but upon error is passed along to error handlers. It can be of any
--   type (including nil).
--
--  With most errors during decoding, this code calls
--
--      JSON:onDecodeError(message, text, location, etc)
--
--  with a message about the error, and if known, the JSON text being parsed and the byte count
--  where the problem was discovered. You can replace the default JSON:onDecodeError() with your
--  own function.
--
--  The default onDecodeError() merely augments the message with data about the text and the
--  location if known (and if a second 'etc' argument had been provided to decode(), its value is
--   tacked onto the message as well), and then calls JSON.assert(), which itself defaults to Lua's
--  built-in assert(), and can also be overridden.
--
--  For example, in an Adobe Lightroom plugin, you might use something like
--
--          function JSON:onDecodeError(message, text, location, etc)
--            LrErrors.throwUserError("Internal Error: invalid JSON data")
--          end
--
--  or even just
--
--          function JSON.assert(message)
--            LrErrors.throwUserError("Internal Error: " .. message)
--          end
--
--  If JSON:decode() is passed a nil, this is called instead:
--
--      JSON:onDecodeOfNilError(message, nil, nil, etc)
--
--  and if JSON:decode() is passed HTML instead of JSON, this is called:
--
--      JSON:onDecodeOfHTMLError(message, text, nil, etc)
--
--   The use of the fourth 'etc' argument allows stronger coordination between decoding and error
--  reporting, especially when you provide your own error-handling routines. Continuing with the
--  the Adobe Lightroom plugin example:
--
--          function JSON:onDecodeError(message, text, location, etc)
--            local note = "Internal Error: invalid JSON data"
--            if type(etc) = 'table' and etc.photo then
--                note = note .. " while processing for " .. etc.photo:getFormattedMetadata('fileName')
--            end
--            LrErrors.throwUserError(note)
--          end
--
--            :
--            :
--
--          for i, photo in ipairs(photosToProcess) do
--              :           
--              :           
--              local data = JSON:decode(someJsonText, { photo = photo })
--              :           
--              :           
--          end
--
--
--
--
 
-- DECODING AND STRICT TYPES
--
--  Because both JSON objects and JSON arrays are converted to Lua tables, it's not normally
--  possible to tell which a Lua table came from, or guarantee decode-encode round-trip
--  equivalency.
--
--  However, if you enable strictTypes, e.g.
--
--      JSON = (loadfile "JSON.lua")() --load the routines
--      JSON.strictTypes = true
--
--  then the Lua table resulting from the decoding of a JSON object or JSON array is marked via Lua
--   metatable, so that when re-encoded with JSON:encode() it ends up as the appropriate JSON type.
--
--  (This is not the default because other routines may not work well with tables that have a
--  metatable set, for example, Lightroom API calls.)
--
--
-- The above copyright notice and this permission notice shall be included in all
-- copies or substantial portions of the Software.
--
--
-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-- ENCODING
-- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
-- SOFTWARE.
--
--
p = {}
--  JSON = (loadfile "JSON.lua")() -- one-time load of the routines
--
--  local raw_json_text    = JSON:encode(lua_table_or_value)
--  local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability


function p.getJson()  
--  On error during encoding, this code calls:
--
--    JSON:onEncodeError(message, etc)
--
--  which you can override in your local JSON object.
--
--
-- SUMMARY OF METHODS YOU CAN OVERRIDE IN YOUR LOCAL LUA JSON OBJECT
--
--    assert
--    onDecodeError
--    onDecodeOfNilError
--    onDecodeOfHTMLError
--    onEncodeError
--
--  If you want to create a separate Lua JSON object with its own error handlers,
--  you can reload JSON.lua or use the :new() method.
--
---------------------------------------------------------------------------


local json = { _version = "0.1.2" }


-------------------------------------------------------------------------------
local author = "-[ JSON.lua package by Jeffrey Friedl (http://regex.info/blog/lua/json), version " .. tostring(VERSION) .. " ]-"
-- Encode
local isArray  = { __tostring = function() return "JSON array"  end }    isArray.__index  = isArray
-------------------------------------------------------------------------------
local isObject = { __tostring = function() return "JSON object" end }    isObject.__index = isObject


local encode


local escape_char_map = {
function OBJDEF:newArray(tbl)
  [ "\\" ] = "\\",
  return setmetatable(tbl or {}, isArray)
  [ "\"" ] = "\"",
end
  [ "\b" ] = "b",
  [ "\f" ] = "f",
  [ "\n" ] = "n",
  [ "\r" ] = "r",
  [ "\t" ] = "t",
}


local escape_char_map_inv = { [ "/" ] = "/" }
function OBJDEF:newObject(tbl)
for k, v in pairs(escape_char_map) do
  return setmetatable(tbl or {}, isObject)
  escape_char_map_inv[v] = k
end
end


local function unicode_codepoint_as_utf8(codepoint)
  --
  -- codepoint is a number
  --
  if codepoint <= 127 then
      return string.char(codepoint)
  elseif codepoint <= 2047 then
      --
      -- 110yyyxx 10xxxxxx        <-- useful notation from http://en.wikipedia.org/wiki/Utf8
      --
      local highpart = math.floor(codepoint / 0x40)
      local lowpart  = codepoint - (0x40 * highpart)
      return string.char(0xC0 + highpart,
                        0x80 + lowpart)
  elseif codepoint <= 65535 then
      --
      -- 1110yyyy 10yyyyxx 10xxxxxx
      --
      local highpart  = math.floor(codepoint / 0x1000)
      local remainder = codepoint - 0x1000 * highpart
      local midpart  = math.floor(remainder / 0x40)
      local lowpart  = remainder - 0x40 * midpart
      highpart = 0xE0 + highpart
      midpart  = 0x80 + midpart
      lowpart  = 0x80 + lowpart
      --
      -- Check for an invalid character (thanks Andy R. at Adobe).
      -- See table 3.7, page 93, in http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf#G28070
      --
      if ( highpart == 0xE0 and midpart < 0xA0 ) or
        ( highpart == 0xED and midpart > 0x9F ) or
        ( highpart == 0xF0 and midpart < 0x90 ) or
        ( highpart == 0xF4 and midpart > 0x8F )
      then
        return "?"
      else
        return string.char(highpart,
                            midpart,
                            lowpart)
      end


local function escape_char(c)
  else
  return "\\" .. (escape_char_map[c] or string.format("u%04x", c:byte()))
      --
      -- 11110zzz 10zzyyyy 10yyyyxx 10xxxxxx
      --
      local highpart  = math.floor(codepoint / 0x40000)
      local remainder = codepoint - 0x40000 * highpart
      local midA      = math.floor(remainder / 0x1000)
      remainder      = remainder - 0x1000 * midA
      local midB      = math.floor(remainder / 0x40)
      local lowpart  = remainder - 0x40 * midB
 
      return string.char(0xF0 + highpart,
                        0x80 + midA,
                        0x80 + midB,
                        0x80 + lowpart)
  end
end
end


function OBJDEF:onDecodeError(message, text, location, etc)
  if text then
      if location then
        message = string.format("%s at char %d of: %s", message, location, text)
      else
        message = string.format("%s: %s", message, text)
      end
  end
  if etc ~= nil then
      message = message .. " (" .. OBJDEF:encode(etc) .. ")"
  end


local function encode_nil(val)
  if self.assert then
  return "null"
      self.assert(false, message)
  else
      assert(false, message)
  end
end
end


OBJDEF.onDecodeOfNilError  = OBJDEF.onDecodeError
OBJDEF.onDecodeOfHTMLError = OBJDEF.onDecodeError


local function encode_table(val, stack)
function OBJDEF:onEncodeError(message, etc)
  local res = {}
  if etc ~= nil then
  stack = stack or {}
      message = message .. " (" .. OBJDEF:encode(etc) .. ")"
  end


  -- Circular reference?
  if self.assert then
  if stack[val] then error("circular reference") end
      self.assert(false, message)
  else
      assert(false, message)
  end
end
 
local function grok_number(self, text, start, etc)
  --
  -- Grab the integer part
  --
  local integer_part = text:match('^-?[1-9]%d*', start)
                    or text:match("^-?0",        start)
 
  if not integer_part then
      self:onDecodeError("expected number", text, start, etc)
  end
 
  local i = start + integer_part:len()
 
  --
  -- Grab an optional decimal part
  --
  local decimal_part = text:match('^%.%d+', i) or ""
 
  i = i + decimal_part:len()


  stack[val] = true
  --
  -- Grab an optional exponential part
  --
  local exponent_part = text:match('^[eE][-+]?%d+', i) or ""


  if rawget(val, 1) ~= nil or next(val) == nil then
  i = i + exponent_part:len()
    -- Treat as array -- check keys are valid and it is not sparse
 
    local n = 0
  local full_number_text = integer_part .. decimal_part .. exponent_part
    for k in pairs(val) do
  local as_number = tonumber(full_number_text)
       if type(k) ~= "number" then
 
        error("invalid table: mixed or invalid key types")
  if not as_number then
      self:onDecodeError("bad number", text, start, etc)
  end
 
  return as_number, i
end
 
 
local function grok_string(self, text, start, etc)
 
  if text:sub(start,start) ~= '"' then
      self:onDecodeError("expected string's opening quote", text, start, etc)
  end
 
  local i = start + 1 -- +1 to bypass the initial quote
  local text_len = text:len()
  local VALUE = ""
  while i <= text_len do
       local c = text:sub(i,i)
      if c == '"' then
        return VALUE, i + 1
       end
       end
       n = n + 1
       if c ~= '\\' then
    end
        VALUE = VALUE .. c
    if n ~= #val then
        i = i + 1
       error("invalid table: sparse array")
      elseif text:match('^\\b', i) then
    end
        VALUE = VALUE .. "\b"
    -- Encode
        i = i + 2
    for i, v in ipairs(val) do
       elseif text:match('^\\f', i) then
       table.insert(res, encode(v, stack))
        VALUE = VALUE .. "\f"
    end
        i = i + 2
    stack[val] = nil
      elseif text:match('^\\n', i) then
    return "[" .. table.concat(res, ",") .. "]"
        VALUE = VALUE .. "\n"
        i = i + 2
       elseif text:match('^\\r', i) then
        VALUE = VALUE .. "\r"
        i = i + 2
      elseif text:match('^\\t', i) then
        VALUE = VALUE .. "\t"
        i = i + 2
      else
        local hex = text:match('^\\u([0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i)
        if hex then
            i = i + 6 -- bypass what we just read


  else
            -- We have a Unicode codepoint. It could be standalone, or if in the proper range and
    -- Treat as an object
            -- followed by another in a specific range, it'll be a two-code surrogate pair.
    for k, v in pairs(val) do
            local codepoint = tonumber(hex, 16)
      if type(k) ~= "string" then
            if codepoint >= 0xD800 and codepoint <= 0xDBFF then
        error("invalid table: mixed or invalid key types")
              -- it's a hi surrogate... see whether we have a following low
              local lo_surrogate = text:match('^\\u([dD][cdefCDEF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i)
              if lo_surrogate then
                  i = i + 6 -- bypass the low surrogate we just read
                  codepoint = 0x2400 + (codepoint - 0xD800) * 0x400 + tonumber(lo_surrogate, 16)
              else
                  -- not a proper low, so we'll just leave the first codepoint as is and spit it out.
              end
            end
            VALUE = VALUE .. unicode_codepoint_as_utf8(codepoint)
 
        else
 
            -- just pass through what's escaped
            VALUE = VALUE .. text:match('^\\(.)', i)
            i = i + 2
        end
       end
       end
      table.insert(res, encode(k, stack) .. ":" .. encode(v, stack))
  end
    end
 
    stack[val] = nil
  self:onDecodeError("unclosed string", text, start, etc)
    return "{" .. table.concat(res, ",") .. "}"
  end
end
end


local function skip_whitespace(text, start)


local function encode_string(val)
  local match_start, match_end = text:find("^[ \n\r\t]+", start) -- [http://www.ietf.org/rfc/rfc4627.txt] Section 2
  return '"' .. val:gsub('[%z\1-\31\\"]', escape_char) .. '"'
  if match_end then
      return match_end + 1
  else
      return start
  end
end
end


local grok_one -- assigned later
local function grok_object(self, text, start, etc)
  if not text:sub(start,start) == '{' then
      self:onDecodeError("expected '{'", text, start, etc)
  end
  local i = skip_whitespace(text, start + 1) -- +1 to skip the '{'
  local VALUE = self.strictTypes and self:newObject { } or { }
  if text:sub(i,i) == '}' then
      return VALUE, i + 1
  end
  local text_len = text:len()
  while i <= text_len do
      local key, new_i = grok_string(self, text, i, etc)
      i = skip_whitespace(text, new_i)
      if text:sub(i, i) ~= ':' then
        self:onDecodeError("expected colon", text, i, etc)
      end
      i = skip_whitespace(text, i + 1)
      local val, new_i = grok_one(self, text, i)
      VALUE[key] = val
      --
      -- Expect now either '}' to end things, or a ',' to allow us to continue.
      --
      i = skip_whitespace(text, new_i)
      local c = text:sub(i,i)
      if c == '}' then
        return VALUE, i + 1
      end
      if text:sub(i, i) ~= ',' then
        self:onDecodeError("expected comma or '}'", text, i, etc)
      end
      i = skip_whitespace(text, i + 1)
  end


local function encode_number(val)
  self:onDecodeError("unclosed '{'", text, start, etc)
  -- Check for NaN, -inf and inf
  if val ~= val or val <= -math.huge or val >= math.huge then
    error("unexpected number value '" .. tostring(val) .. "'")
  end
  return string.format("%.14g", val)
end
end


local function grok_array(self, text, start, etc)
  if not text:sub(start,start) == '[' then
      self:onDecodeError("expected '['", text, start, etc)
  end


local type_func_map = {
  local i = skip_whitespace(text, start + 1) -- +1 to skip the '['
  [ "nil"    ] = encode_nil,
  local VALUE = self.strictTypes and self:newArray { } or { }
  [ "table"  ] = encode_table,
  if text:sub(i,i) == ']' then
  [ "string"  ] = encode_string,
      return VALUE, i + 1
  [ "number"  ] = encode_number,
  end
  [ "boolean" ] = tostring,
}


  local text_len = text:len()
  while i <= text_len do
      local val, new_i = grok_one(self, text, i)


encode = function(val, stack)
      table.insert(VALUE, val)
  local t = type(val)
 
  local f = type_func_map[t]
      i = skip_whitespace(text, new_i)
  if f then
 
    return f(val, stack)
      --
  end
      -- Expect now either ']' to end things, or a ',' to allow us to continue.
  error("unexpected type '" .. t .. "'")
      --
      local c = text:sub(i,i)
      if c == ']' then
        return VALUE, i + 1
      end
      if text:sub(i, i) ~= ',' then
        self:onDecodeError("expected comma or '['", text, i, etc)
      end
      i = skip_whitespace(text, i + 1)
  end
  self:onDecodeError("unclosed '['", text, start, etc)
end
end




function json.encode(val)
grok_one = function(self, text, start, etc)
  return ( encode(val) )
  -- Skip any whitespace
end
  start = skip_whitespace(text, start)
 
  if start > text:len() then
      self:onDecodeError("unexpected end of string", text, nil, etc)
  end
 
  if text:find('^"', start) then
      return grok_string(self, text, start, etc)
 
  elseif text:find('^[-0123456789 ]', start) then
      return grok_number(self, text, start, etc)
 
  elseif text:find('^%{', start) then
      return grok_object(self, text, start, etc)
 
  elseif text:find('^%[', start) then
      return grok_array(self, text, start, etc)


  elseif text:find('^true', start) then
      return true, start + 4


-------------------------------------------------------------------------------
  elseif text:find('^false', start) then
-- Decode
      return false, start + 5
-------------------------------------------------------------------------------


local parse
  elseif text:find('^null', start) then
      return nil, start + 4


local function create_set(...)
  else
  local res = {}
      self:onDecodeError("can't parse JSON", text, start, etc)
  for i = 1, select("#", ...) do
  end
    res[ select(i, ...) ] = true
  end
  return res
end
end


local space_chars  = create_set(" ", "\t", "\r", "\n")
function OBJDEF:decode(text, etc)
local delim_chars  = create_set(" ", "\t", "\r", "\n", "]", "}", ",")
  if type(self) ~= 'table' or self.__index ~= OBJDEF then
local escape_chars  = create_set("\\", "/", '"', "b", "f", "n", "r", "t", "u")
      OBJDEF:onDecodeError("JSON:decode must be called in method format", nil, nil, etc)
local literals      = create_set("true", "false", "null")
  end


local literal_map = {
  if text == nil then
  [ "true" ] = true,
      self:onDecodeOfNilError(string.format("nil passed to JSON:decode()"), nil, nil, etc)
  [ "false" ] = false,
  elseif type(text) ~= 'string' then
  [ "null" ] = nil,
      self:onDecodeError(string.format("expected string argument to JSON:decode(), got %s", type(text)), nil, nil, etc)
}
  end


  if text:match('^%s*$') then
      return nil
  end


local function next_char(str, idx, set, negate)
  if text:match('^%s*<') then
  for i = idx, #str do
      -- Can't be JSON... we'll assume it's HTML
    if set[str:sub(i, i)] ~= negate then
      self:onDecodeOfHTMLError(string.format("html passed to JSON:decode()"), text, nil, etc)
       return i
  end
    end
 
  end
  --
  return #str + 1
  -- Ensure that it's not UTF-32 or UTF-16.
  -- Those are perfectly valid encodings for JSON (as per RFC 4627 section 3),
  -- but this package can't handle them.
  --
  if text:sub(1,1):byte() == 0 or (text:len() >= 2 and text:sub(2,2):byte() == 0) then
      self:onDecodeError("JSON package groks only UTF-8, sorry", text, nil, etc)
  end
 
  local success, value = pcall(grok_one, self, text, 1, etc)
  if success then
       return value
  else
      -- should never get here... JSON parse errors should have been caught earlier
      assert(false, value)
      return nil
  end
end
end


local function backslash_replacement_function(c)
  if c == "\n" then
      return "\\n"
  elseif c == "\r" then
      return "\\r"
  elseif c == "\t" then
      return "\\t"
  elseif c == "\b" then
      return "\\b"
  elseif c == "\f" then
      return "\\f"
  elseif c == '"' then
      return '\\"'
  elseif c == '\\' then
      return '\\\\'
  else
      return string.format("\\u%04x", c:byte())
  end
end


local function decode_error(str, idx, msg)
local chars_to_be_escaped_in_JSON_string
  local line_count = 1
  = '['
   local col_count = 1
  ..    '"'    -- class sub-pattern to match a double quote
  for i = 1, idx - 1 do
  ..    '%\\'  -- class sub-pattern to match a backslash
    col_count = col_count + 1
  ..    '%z'   -- class sub-pattern to match a null
    if str:sub(i, i) == "\n" then
  ..    '\001' .. '-' .. '\031' -- class sub-pattern to match control characters
      line_count = line_count + 1
  .. ']'
      col_count = 1
 
    end
local function json_string_literal(value)
  end
  local newval = value:gsub(chars_to_be_escaped_in_JSON_string, backslash_replacement_function)
  error( string.format("%s at line %d col %d", msg, line_count, col_count) )
  return '"' .. newval .. '"'
end
end


local function object_or_array(self, T, etc)
  --
  -- We need to inspect all the keys... if there are any strings, we'll convert to a JSON
  -- object. If there are only numbers, it's a JSON array.
  --
  -- If we'll be converting to a JSON object, we'll want to sort the keys so that the
  -- end result is deterministic.
  --
  local string_keys = { }
  local seen_number_key = false
  local maximum_number_key


local function codepoint_to_utf8(n)
  for key in pairs(T) do
  -- http://scripts.sil.org/cms/scripts/page.php?site_id=nrsi&id=iws-appendixa
      if type(key) == 'number' then
  local f = math.floor
        seen_number_key = true
  if n <= 0x7f then
        if not maximum_number_key or maximum_number_key < key then
    return string.char(n)
            maximum_number_key = key
  elseif n <= 0x7ff then
        end
    return string.char(f(n / 64) + 192, n % 64 + 128)
      elseif type(key) == 'string' then
  elseif n <= 0xffff then
        table.insert(string_keys, key)
    return string.char(f(n / 4096) + 224, f(n % 4096 / 64) + 128, n % 64 + 128)
      else
  elseif n <= 0x10ffff then
        self:onEncodeError("can't encode table with a key of type " .. type(key), etc)
    return string.char(f(n / 262144) + 240, f(n % 262144 / 4096) + 128,
      end
                      f(n % 4096 / 64) + 128, n % 64 + 128)
  end
  end
 
  error( string.format("invalid unicode codepoint '%x'", n) )
  if seen_number_key and #string_keys > 0 then
      --
      -- Mixed key types... don't know what to do, so bail
      --
      self:onEncodeError("a table with both numeric and string keys could be an object or array; aborting", etc)
 
  elseif #string_keys == 0  then
      --
      -- An array
      --
      if seen_number_key then
        return nil, maximum_number_key -- an array
      else
        --
        -- An empty table...
        --
        if tostring(T) == "JSON array" then
            return nil
        elseif tostring(T) == "JSON object" then
            return { }
        else
            -- have to guess, so we'll pick array, since empty arrays are likely more common than empty objects
            return nil
        end
      end
  else
      --
      -- An object, so return a list of keys
      --
      table.sort(string_keys)
      return string_keys
  end
end
end


--
-- Encode
--
local encode_value -- must predeclare because it calls itself
function encode_value(self, value, parents, etc)


local function parse_unicode_escape(s)
  local n1 = tonumber( s:sub(1, 4),  16 )
  local n2 = tonumber( s:sub(7, 10), 16 )
  -- Surrogate pair?
  if n2 then
    return codepoint_to_utf8((n1 - 0xd800) * 0x400 + (n2 - 0xdc00) + 0x10000)
  else
    return codepoint_to_utf8(n1)
  end
end


  if value == nil then
      return 'null'
  end


local function parse_string(str, i)
  if type(value) == 'string' then
  local res = ""
      return json_string_literal(value)
  local j = i + 1
  elseif type(value) == 'number' then
  local k = j
      if value ~= value then
        --
        -- NaN (Not a Number).
        -- JSON has no NaN, so we have to fudge the best we can. This should really be a package option.
        --
        return "null"
      elseif value >= math.huge then
        --
        -- Positive infinity. JSON has no INF, so we have to fudge the best we can. This should
        -- really be a package option. Note: at least with some implementations, positive infinity
        -- is both ">= math.huge" and "<= -math.huge", which makes no sense but that's how it is.
        -- Negative infinity is properly "<= -math.huge". So, we must be sure to check the ">="
        -- case first.
        --
        return "1e+9999"
      elseif value <= -math.huge then
        --
        -- Negative infinity.
        -- JSON has no INF, so we have to fudge the best we can. This should really be a package option.
        --
        return "-1e+9999"
      else
        return tostring(value)
      end
  elseif type(value) == 'boolean' then
      return tostring(value)


  while j <= #str do
  elseif type(value) ~= 'table' then
    local x = str:byte(j)
      self:onEncodeError("can't convert " .. type(value) .. " to JSON", etc)


    if x < 32 then
  else
       decode_error(str, j, "control character in string")
       --
      -- A table to be converted to either a JSON object or array.
      --
      local T = value


    elseif x == 92 then -- `\`: Escape
       if parents[T] then
      res = res .. str:sub(k, j - 1)
        self:onEncodeError("table " .. tostring(T) .. " is a child of itself", etc)
      j = j + 1
      local c = str:sub(j, j)
       if c == "u" then
        local hex = str:match("^[dD][89aAbB]%x%x\\u%x%x%x%x", j + 1)
                or str:match("^%x%x%x%x", j + 1)
                or decode_error(str, j - 1, "invalid unicode escape in string")
        res = res .. parse_unicode_escape(hex)
        j = j + #hex
       else
       else
        if not escape_chars[c] then
        parents[T] = true
          decode_error(str, j - 1, "invalid escape char '" .. c .. "' in string")
        end
        res = res .. escape_char_map_inv[c]
       end
       end
      k = j + 1


    elseif x == 34 then -- `"`: End of string
      local result_value
      res = res .. str:sub(k, j - 1)
 
       return res, j + 1
      local object_keys, maximum_number_key = object_or_array(self, T, etc)
    end
      if maximum_number_key then
        --
        -- An array...
        --
        local ITEMS = { }
        for i = 1, maximum_number_key do
            table.insert(ITEMS, encode_value(self, T[i], parents, etc))
        end
 
        result_value = "[" .. table.concat(ITEMS, ",") .. "]"
       elseif object_keys then
        --
        -- An object
        --


    j = j + 1
        --
  end
        -- We'll always sort the keys, so that comparisons can be made on
        -- the results, etc. The actual order is not particularly
        -- important (e.g. it doesn't matter what character set we sort
        -- as); it's only important that it be deterministic... the same
        -- every time.
        --
        local PARTS = { }
        for _, key in ipairs(object_keys) do
            local encoded_key = encode_value(self, tostring(key), parents, etc)
            local encoded_val = encode_value(self, T[key],        parents, etc)
            table.insert(PARTS, string.format("%s:%s", encoded_key, encoded_val))
        end
        result_value = "{" .. table.concat(PARTS, ",") .. "}"
      else
        --
        -- An empty array/object... we'll treat it as an array, though it should really be an option
        --
        result_value = "[]"
      end


  decode_error(str, i, "expected closing quote for string")
      parents[T] = false
      return result_value
  end
end
end


local encode_pretty_value -- must predeclare because it calls itself
function encode_pretty_value(self, value, parents, indent, etc)
  if type(value) == 'string' then
      return json_string_literal(value)
  elseif type(value) == 'number' then
      return tostring(value)
  elseif type(value) == 'boolean' then
      return tostring(value)
  elseif type(value) == 'nil' then
      return 'null'
  elseif type(value) ~= 'table' then
      self:onEncodeError("can't convert " .. type(value) .. " to JSON", etc)
  else
      --
      -- A table to be converted to either a JSON object or array.
      --
      local T = value
      if parents[T] then
        self:onEncodeError("table " .. tostring(T) .. " is a child of itself", etc)
      end
      parents[T] = true
      local result_value


local function parse_number(str, i)
      local object_keys = object_or_array(self, T, etc)
  local x = next_char(str, i, delim_chars)
      if not object_keys then
  local s = str:sub(i, x - 1)
        --
  local n = tonumber(s)
        -- An array...
  if not n then
        --
    decode_error(str, i, "invalid number '" .. s .. "'")
        local ITEMS = { }
  end
        for i = 1, #T do
  return n, x
            table.insert(ITEMS, encode_pretty_value(self, T[i], parents, indent, etc))
end
        end
 
        result_value = "[ " .. table.concat(ITEMS, ", ") .. " ]"
 
      else


        --
        -- An object -- can keys be numbers?
        --


local function parse_literal(str, i)
        local KEYS = { }
  local x = next_char(str, i, delim_chars)
        local max_key_length = 0
  local word = str:sub(i, x - 1)
        for _, key in ipairs(object_keys) do
  if not literals[word] then
            local encoded = encode_pretty_value(self, tostring(key), parents, "", etc)
    decode_error(str, i, "invalid literal '" .. word .. "'")
            max_key_length = math.max(max_key_length, #encoded)
  end
            table.insert(KEYS, encoded)
  return literal_map[word], x
        end
end
        local key_indent = indent .. "    "
        local subtable_indent = indent .. string.rep(" ", max_key_length + 2 + 4)
        local FORMAT = "%s%" .. tostring(max_key_length) .. "s: %s"


        local COMBINED_PARTS = { }
        for i, key in ipairs(object_keys) do
            local encoded_val = encode_pretty_value(self, T[key], parents, subtable_indent, etc)
            table.insert(COMBINED_PARTS, string.format(FORMAT, key_indent, KEYS[i], encoded_val))
        end
        result_value = "{\n" .. table.concat(COMBINED_PARTS, ",\n") .. "\n" .. indent .. "}"
      end


local function parse_array(str, i)
       parents[T] = false
  local res = {}
      return result_value
  local n = 1
  end
  i = i + 1
  while 1 do
    local x
    i = next_char(str, i, space_chars, true)
    -- Empty / end of array?
    if str:sub(i, i) == "]" then
      i = i + 1
       break
    end
    -- Read token
    x, i = parse(str, i)
    res[n] = x
    n = n + 1
    -- Next token
    i = next_char(str, i, space_chars, true)
    local chr = str:sub(i, i)
    i = i + 1
    if chr == "]" then break end
    if chr ~= "," then decode_error(str, i, "expected ']' or ','") end
  end
  return res, i
end
end


function OBJDEF:encode(value, etc)
  if type(self) ~= 'table' or self.__index ~= OBJDEF then
      OBJDEF:onEncodeError("JSON:encode must be called in method format", etc)
  end


local function parse_object(str, i)
  local parents = {}
  local res = {}
  return encode_value(self, value, parents, etc)
  i = i + 1
  while 1 do
    local key, val
    i = next_char(str, i, space_chars, true)
    -- Empty / end of object?
    if str:sub(i, i) == "}" then
      i = i + 1
      break
    end
    -- Read key
    if str:sub(i, i) ~= '"' then
      decode_error(str, i, "expected string for key")
    end
    key, i = parse(str, i)
    -- Read ':' delimiter
    i = next_char(str, i, space_chars, true)
    if str:sub(i, i) ~= ":" then
      decode_error(str, i, "expected ':' after key")
    end
    i = next_char(str, i + 1, space_chars, true)
    -- Read value
    val, i = parse(str, i)
    -- Set
    res[key] = val
    -- Next token
    i = next_char(str, i, space_chars, true)
    local chr = str:sub(i, i)
    i = i + 1
    if chr == "}" then break end
    if chr ~= "," then decode_error(str, i, "expected '}' or ','") end
  end
  return res, i
end
end


function OBJDEF:encode_pretty(value, etc)
  local parents = {}
  local subtable_indent = ""
  return encode_pretty_value(self, value, parents, subtable_indent, etc)
end


local char_func_map = {
function OBJDEF.__tostring()
  [ '"' ] = parse_string,
  return "JSON encode/decode package"
  [ "0" ] = parse_number,
end
  [ "1" ] = parse_number,
  [ "2" ] = parse_number,
  [ "3" ] = parse_number,
  [ "4" ] = parse_number,
  [ "5" ] = parse_number,
  [ "6" ] = parse_number,
  [ "7" ] = parse_number,
  [ "8" ] = parse_number,
  [ "9" ] = parse_number,
  [ "-" ] = parse_number,
  [ "t" ] = parse_literal,
  [ "f" ] = parse_literal,
  [ "n" ] = parse_literal,
  [ "[" ] = parse_array,
  [ "{" ] = parse_object,
}


OBJDEF.__index = OBJDEF


parse = function(str, idx)
function OBJDEF:new(args)
  local chr = str:sub(idx, idx)
  local new = { }
  local f = char_func_map[chr]
  if f then
    return f(str, idx)
  end
  decode_error(str, idx, "unexpected character '" .. chr .. "'")
end


  if args then
      for key, val in pairs(args) do
        new[key] = val
      end
  end


function json.decode(str)
  return setmetatable(new, OBJDEF)
  if type(str) ~= "string" then
    error("expected argument of type string, got " .. type(str))
  end
  local res, idx = parse(str, next_char(str, 1, space_chars, true))
  idx = next_char(str, idx, space_chars, true)
  if idx <= #str then
    decode_error(str, idx, "trailing garbage")
  end
  return res
end
end


return OBJDEF:new()


return json
--
end
-- Version history:
--
--  20130120.6    Comment update: added a link to the specific page on my blog where this code can
--                be found, so that folks who come across the code outside of my blog can find updates
--                more easily.
--
--  20111207.5    Added support for the 'etc' arguments, for better error reporting.
--
--  20110731.4    More feedback from David Kolf on how to make the tests for Nan/Infinity system independent.
--
--  20110730.3    Incorporated feedback from David Kolf at http://lua-users.org/wiki/JsonModules:
--
--                  * When encoding lua for JSON, Sparse numeric arrays are now handled by
--                    spitting out full arrays, such that
--                        JSON:encode({"one", "two", [10] = "ten"})
--                    returns
--                        ["one","two",null,null,null,null,null,null,null,"ten"]
--
--                    In 20100810.2 and earlier, only up to the first non-null value would have been retained.
--
--                  * When encoding lua for JSON, numeric value NaN gets spit out as null, and infinity as "1+e9999".
--                    Version 20100810.2 and earlier created invalid JSON in both cases.
--
--                  * Unicode surrogate pairs are now detected when decoding JSON.
--
--  20100810.2    added some checking to ensure that an invalid Unicode character couldn't leak in to the UTF-8 encoding
--
--  20100731.1    initial public release
--