· 4 years ago · Feb 01, 2021, 12:46 AM
1-- -*- coding: utf-8 -*-
2--
3-- Simple JSON encoding and decoding in pure Lua.
4--
5-- Copyright 2010-2016 Jeffrey Friedl
6-- http://regex.info/blog/
7-- Latest version: http://regex.info/blog/lua/json
8--
9-- This code is released under a Creative Commons CC-BY "Attribution" License:
10-- http://creativecommons.org/licenses/by/3.0/deed.en_US
11--
12-- It can be used for any purpose so long as:
13-- 1) the copyright notice above is maintained
14-- 2) the web-page links above are maintained
15-- 3) the 'AUTHOR_NOTE' string below is maintained
16--
17local VERSION = '20161109.21' -- version history at end of file
18local AUTHOR_NOTE = "-[ JSON.lua package by Jeffrey Friedl (http://regex.info/blog/lua/json) version 20161109.21 ]-"
19
20--
21-- The 'AUTHOR_NOTE' variable exists so that information about the source
22-- of the package is maintained even in compiled versions. It's also
23-- included in OBJDEF below mostly to quiet warnings about unused variables.
24--
25local OBJDEF = {
26 VERSION = VERSION,
27 AUTHOR_NOTE = AUTHOR_NOTE,
28}
29
30
31--
32-- Simple JSON encoding and decoding in pure Lua.
33-- JSON definition: http://www.json.org/
34--
35--
36-- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
37--
38-- local lua_value = JSON:decode(raw_json_text)
39--
40-- local raw_json_text = JSON:encode(lua_table_or_value)
41-- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability
42--
43--
44--
45-- DECODING (from a JSON string to a Lua table)
46--
47--
48-- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
49--
50-- local lua_value = JSON:decode(raw_json_text)
51--
52-- If the JSON text is for an object or an array, e.g.
53-- { "what": "books", "count": 3 }
54-- or
55-- [ "Larry", "Curly", "Moe" ]
56--
57-- the result is a Lua table, e.g.
58-- { what = "books", count = 3 }
59-- or
60-- { "Larry", "Curly", "Moe" }
61--
62--
63-- The encode and decode routines accept an optional second argument,
64-- "etc", which is not used during encoding or decoding, but upon error
65-- is passed along to error handlers. It can be of any type (including nil).
66--
67--
68--
69-- ERROR HANDLING
70--
71-- With most errors during decoding, this code calls
72--
73-- JSON:onDecodeError(message, text, location, etc)
74--
75-- with a message about the error, and if known, the JSON text being
76-- parsed and the byte count where the problem was discovered. You can
77-- replace the default JSON:onDecodeError() with your own function.
78--
79-- The default onDecodeError() merely augments the message with data
80-- about the text and the location if known (and if a second 'etc'
81-- argument had been provided to decode(), its value is tacked onto the
82-- message as well), and then calls JSON.assert(), which itself defaults
83-- to Lua's built-in assert(), and can also be overridden.
84--
85-- For example, in an Adobe Lightroom plugin, you might use something like
86--
87-- function JSON:onDecodeError(message, text, location, etc)
88-- LrErrors.throwUserError("Internal Error: invalid JSON data")
89-- end
90--
91-- or even just
92--
93-- function JSON.assert(message)
94-- LrErrors.throwUserError("Internal Error: " .. message)
95-- end
96--
97-- If JSON:decode() is passed a nil, this is called instead:
98--
99-- JSON:onDecodeOfNilError(message, nil, nil, etc)
100--
101-- and if JSON:decode() is passed HTML instead of JSON, this is called:
102--
103-- JSON:onDecodeOfHTMLError(message, text, nil, etc)
104--
105-- The use of the fourth 'etc' argument allows stronger coordination
106-- between decoding and error reporting, especially when you provide your
107-- own error-handling routines. Continuing with the the Adobe Lightroom
108-- plugin example:
109--
110-- function JSON:onDecodeError(message, text, location, etc)
111-- local note = "Internal Error: invalid JSON data"
112-- if type(etc) = 'table' and etc.photo then
113-- note = note .. " while processing for " .. etc.photo:getFormattedMetadata('fileName')
114-- end
115-- LrErrors.throwUserError(note)
116-- end
117--
118-- :
119-- :
120--
121-- for i, photo in ipairs(photosToProcess) do
122-- :
123-- :
124-- local data = JSON:decode(someJsonText, { photo = photo })
125-- :
126-- :
127-- end
128--
129--
130--
131-- If the JSON text passed to decode() has trailing garbage (e.g. as with the JSON "[123]xyzzy"),
132-- the method
133--
134-- JSON:onTrailingGarbage(json_text, location, parsed_value, etc)
135--
136-- is invoked, where:
137--
138-- json_text is the original JSON text being parsed,
139-- location is the count of bytes into json_text where the garbage starts (6 in the example),
140-- parsed_value is the Lua result of what was successfully parsed ({123} in the example),
141-- etc is as above.
142--
143-- If JSON:onTrailingGarbage() does not abort, it should return the value decode() should return,
144-- or nil + an error message.
145--
146-- local new_value, error_message = JSON:onTrailingGarbage()
147--
148-- The default handler just invokes JSON:onDecodeError("trailing garbage"...), but you can have
149-- this package ignore trailing garbage via
150--
151-- function JSON:onTrailingGarbage(json_text, location, parsed_value, etc)
152-- return parsed_value
153-- end
154--
155--
156-- DECODING AND STRICT TYPES
157--
158-- Because both JSON objects and JSON arrays are converted to Lua tables,
159-- it's not normally possible to tell which original JSON type a
160-- particular Lua table was derived from, or guarantee decode-encode
161-- round-trip equivalency.
162--
163-- However, if you enable strictTypes, e.g.
164--
165-- JSON = assert(loadfile "JSON.lua")() --load the routines
166-- JSON.strictTypes = true
167--
168-- then the Lua table resulting from the decoding of a JSON object or
169-- JSON array is marked via Lua metatable, so that when re-encoded with
170-- JSON:encode() it ends up as the appropriate JSON type.
171--
172-- (This is not the default because other routines may not work well with
173-- tables that have a metatable set, for example, Lightroom API calls.)
174--
175--
176-- ENCODING (from a lua table to a JSON string)
177--
178-- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
179--
180-- local raw_json_text = JSON:encode(lua_table_or_value)
181-- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability
182-- local custom_pretty = JSON:encode(lua_table_or_value, etc, { pretty = true, indent = "| ", align_keys = false })
183--
184-- On error during encoding, this code calls:
185--
186-- JSON:onEncodeError(message, etc)
187--
188-- which you can override in your local JSON object.
189--
190-- The 'etc' in the error call is the second argument to encode()
191-- and encode_pretty(), or nil if it wasn't provided.
192--
193--
194-- ENCODING OPTIONS
195--
196-- An optional third argument, a table of options, can be provided to encode().
197--
198-- encode_options = {
199-- -- options for making "pretty" human-readable JSON (see "PRETTY-PRINTING" below)
200-- pretty = true,
201-- indent = " ",
202-- align_keys = false,
203-- array_newline = false,
204--
205-- -- other output-related options
206-- null = "\0", -- see "ENCODING JSON NULL VALUES" below
207-- stringsAreUtf8 = false, -- see "HANDLING UNICODE LINE AND PARAGRAPH SEPARATORS FOR JAVA" below
208-- }
209--
210-- json_string = JSON:encode(mytable, etc, encode_options)
211--
212--
213--
214-- For reference, the defaults are:
215--
216-- pretty = false
217-- null = nil,
218-- stringsAreUtf8 = false,
219-- array_newline = false,
220--
221--
222--
223-- PRETTY-PRINTING
224--
225-- Enabling the 'pretty' encode option helps generate human-readable JSON.
226--
227-- pretty = JSON:encode(val, etc, {
228-- pretty = true,
229-- indent = " ",
230-- align_keys = false,
231-- })
232--
233-- encode_pretty() is also provided: it's identical to encode() except
234-- that encode_pretty() provides a default options table if none given in the call:
235--
236-- { pretty = true, align_keys = false, indent = " " }
237--
238-- For example, if
239--
240-- JSON:encode(data)
241--
242-- produces:
243--
244-- {"city":"Kyoto","climate":{"avg_temp":16,"humidity":"high","snowfall":"minimal"},"country":"Japan","wards":11}
245--
246-- then
247--
248-- JSON:encode_pretty(data)
249--
250-- produces:
251--
252-- {
253-- "city": "Kyoto",
254-- "climate": {
255-- "avg_temp": 16,
256-- "humidity": "high",
257-- "snowfall": "minimal"
258-- },
259-- "country": "Japan",
260-- "wards": 11
261-- }
262--
263-- The following three lines return identical results:
264-- JSON:encode_pretty(data)
265-- JSON:encode_pretty(data, nil, { pretty = true, align_keys = false, indent = " " })
266-- JSON:encode (data, nil, { pretty = true, align_keys = false, indent = " " })
267--
268-- An example of setting your own indent string:
269--
270-- JSON:encode_pretty(data, nil, { pretty = true, indent = "| " })
271--
272-- produces:
273--
274-- {
275-- | "city": "Kyoto",
276-- | "climate": {
277-- | | "avg_temp": 16,
278-- | | "humidity": "high",
279-- | | "snowfall": "minimal"
280-- | },
281-- | "country": "Japan",
282-- | "wards": 11
283-- }
284--
285-- An example of setting align_keys to true:
286--
287-- JSON:encode_pretty(data, nil, { pretty = true, indent = " ", align_keys = true })
288--
289-- produces:
290--
291-- {
292-- "city": "Kyoto",
293-- "climate": {
294-- "avg_temp": 16,
295-- "humidity": "high",
296-- "snowfall": "minimal"
297-- },
298-- "country": "Japan",
299-- "wards": 11
300-- }
301--
302-- which I must admit is kinda ugly, sorry. This was the default for
303-- encode_pretty() prior to version 20141223.14.
304--
305--
306-- HANDLING UNICODE LINE AND PARAGRAPH SEPARATORS FOR JAVA
307--
308-- If the 'stringsAreUtf8' encode option is set to true, consider Lua strings not as a sequence of bytes,
309-- but as a sequence of UTF-8 characters.
310--
311-- Currently, the only practical effect of setting this option is that Unicode LINE and PARAGRAPH
312-- separators, if found in a string, are encoded with a JSON escape instead of being dumped as is.
313-- The JSON is valid either way, but encoding this way, apparently, allows the resulting JSON
314-- to also be valid Java.
315--
316-- AMBIGUOUS SITUATIONS DURING THE ENCODING
317--
318-- During the encode, if a Lua table being encoded contains both string
319-- and numeric keys, it fits neither JSON's idea of an object, nor its
320-- idea of an array. To get around this, when any string key exists (or
321-- when non-positive numeric keys exist), numeric keys are converted to
322-- strings.
323--
324-- For example,
325-- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" }))
326-- produces the JSON object
327-- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"}
328--
329-- To prohibit this conversion and instead make it an error condition, set
330-- JSON.noKeyConversion = true
331--
332--
333-- ENCODING JSON NULL VALUES
334--
335-- Lua tables completely omit keys whose value is nil, so without special handling there's
336-- no way to get a field in a JSON object with a null value. For example
337-- JSON:encode({ username = "admin", password = nil })
338-- produces
339-- {"username":"admin"}
340--
341-- In order to actually produce
342-- {"username":"admin", "password":null}
343-- one can include a string value for a "null" field in the options table passed to encode()....
344-- any Lua table entry with that value becomes null in the JSON output:
345-- JSON:encode({ username = "admin", password = "xyzzy" }, nil, { null = "xyzzy" })
346-- produces
347-- {"username":"admin", "password":null}
348--
349-- Just be sure to use a string that is otherwise unlikely to appear in your data.
350-- The string "\0" (a string with one null byte) may well be appropriate for many applications.
351--
352-- The "null" options also applies to Lua tables that become JSON arrays.
353-- JSON:encode({ "one", "two", nil, nil })
354-- produces
355-- ["one","two"]
356-- while
357-- NULL = "\0"
358-- JSON:encode({ "one", "two", NULL, NULL}, nil, { null = NULL })
359-- produces
360-- ["one","two",null,null]
361--
362--
363--
364--
365-- HANDLING LARGE AND/OR PRECISE NUMBERS
366--
367--
368-- Without special handling, numbers in JSON can lose precision in Lua.
369-- For example:
370--
371-- T = JSON:decode('{ "small":12345, "big":12345678901234567890123456789, "precise":9876.67890123456789012345 }')
372--
373-- print("small: ", type(T.small), T.small)
374-- print("big: ", type(T.big), T.big)
375-- print("precise: ", type(T.precise), T.precise)
376--
377-- produces
378--
379-- small: number 12345
380-- big: number 1.2345678901235e+28
381-- precise: number 9876.6789012346
382--
383-- Precision is lost with both 'big' and 'precise'.
384--
385-- This package offers ways to try to handle this better (for some definitions of "better")...
386--
387-- The most precise method is by setting the global:
388--
389-- JSON.decodeNumbersAsObjects = true
390--
391-- When this is set, numeric JSON data is encoded into Lua in a form that preserves the exact
392-- JSON numeric presentation when re-encoded back out to JSON, or accessed in Lua as a string.
393--
394-- (This is done by encoding the numeric data with a Lua table/metatable that returns
395-- the possibly-imprecise numeric form when accessed numerically, but the original precise
396-- representation when accessed as a string. You can also explicitly access
397-- via JSON:forceString() and JSON:forceNumber())
398--
399-- Consider the example above, with this option turned on:
400--
401-- JSON.decodeNumbersAsObjects = true
402--
403-- T = JSON:decode('{ "small":12345, "big":12345678901234567890123456789, "precise":9876.67890123456789012345 }')
404--
405-- print("small: ", type(T.small), T.small)
406-- print("big: ", type(T.big), T.big)
407-- print("precise: ", type(T.precise), T.precise)
408--
409-- This now produces:
410--
411-- small: table 12345
412-- big: table 12345678901234567890123456789
413-- precise: table 9876.67890123456789012345
414--
415-- However, within Lua you can still use the values (e.g. T.precise in the example above) in numeric
416-- contexts. In such cases you'll get the possibly-imprecise numeric version, but in string contexts
417-- and when the data finds its way to this package's encode() function, the original full-precision
418-- representation is used.
419--
420-- Even without using the JSON.decodeNumbersAsObjects option, you can encode numbers
421-- in your Lua table that retain high precision upon encoding to JSON, by using the JSON:asNumber()
422-- function:
423--
424-- T = {
425-- imprecise = 123456789123456789.123456789123456789,
426-- precise = JSON:asNumber("123456789123456789.123456789123456789")
427-- }
428--
429-- print(JSON:encode_pretty(T))
430--
431-- This produces:
432--
433-- {
434-- "precise": 123456789123456789.123456789123456789,
435-- "imprecise": 1.2345678912346e+17
436-- }
437--
438--
439--
440-- A different way to handle big/precise JSON numbers is to have decode() merely return
441-- the exact string representation of the number instead of the number itself.
442-- This approach might be useful when the numbers are merely some kind of opaque
443-- object identifier and you want to work with them in Lua as strings anyway.
444--
445-- This approach is enabled by setting
446--
447-- JSON.decodeIntegerStringificationLength = 10
448--
449-- The value is the number of digits (of the integer part of the number) at which to stringify numbers.
450--
451-- Consider our previous example with this option set to 10:
452--
453-- JSON.decodeIntegerStringificationLength = 10
454--
455-- T = JSON:decode('{ "small":12345, "big":12345678901234567890123456789, "precise":9876.67890123456789012345 }')
456--
457-- print("small: ", type(T.small), T.small)
458-- print("big: ", type(T.big), T.big)
459-- print("precise: ", type(T.precise), T.precise)
460--
461-- This produces:
462--
463-- small: number 12345
464-- big: string 12345678901234567890123456789
465-- precise: number 9876.6789012346
466--
467-- The long integer of the 'big' field is at least JSON.decodeIntegerStringificationLength digits
468-- in length, so it's converted not to a Lua integer but to a Lua string. Using a value of 0 or 1 ensures
469-- that all JSON numeric data becomes strings in Lua.
470--
471-- Note that unlike
472-- JSON.decodeNumbersAsObjects = true
473-- this stringification is simple and unintelligent: the JSON number simply becomes a Lua string, and that's the end of it.
474-- If the string is then converted back to JSON, it's still a string. After running the code above, adding
475-- print(JSON:encode(T))
476-- produces
477-- {"big":"12345678901234567890123456789","precise":9876.6789012346,"small":12345}
478-- which is unlikely to be desired.
479--
480-- There's a comparable option for the length of the decimal part of a number:
481--
482-- JSON.decodeDecimalStringificationLength
483--
484-- This can be used alone or in conjunction with
485--
486-- JSON.decodeIntegerStringificationLength
487--
488-- to trip stringification on precise numbers with at least JSON.decodeIntegerStringificationLength digits after
489-- the decimal point.
490--
491-- This example:
492--
493-- JSON.decodeIntegerStringificationLength = 10
494-- JSON.decodeDecimalStringificationLength = 5
495--
496-- T = JSON:decode('{ "small":12345, "big":12345678901234567890123456789, "precise":9876.67890123456789012345 }')
497--
498-- print("small: ", type(T.small), T.small)
499-- print("big: ", type(T.big), T.big)
500-- print("precise: ", type(T.precise), T.precise)
501--
502-- produces:
503--
504-- small: number 12345
505-- big: string 12345678901234567890123456789
506-- precise: string 9876.67890123456789012345
507--
508--
509--
510--
511--
512-- SUMMARY OF METHODS YOU CAN OVERRIDE IN YOUR LOCAL LUA JSON OBJECT
513--
514-- assert
515-- onDecodeError
516-- onDecodeOfNilError
517-- onDecodeOfHTMLError
518-- onTrailingGarbage
519-- onEncodeError
520--
521-- If you want to create a separate Lua JSON object with its own error handlers,
522-- you can reload JSON.lua or use the :new() method.
523--
524---------------------------------------------------------------------------
525
526local default_pretty_indent = " "
527local default_pretty_options = { pretty = true, align_keys = false, indent = default_pretty_indent }
528
529local isArray = { __tostring = function() return "JSON array" end } isArray.__index = isArray
530local isObject = { __tostring = function() return "JSON object" end } isObject.__index = isObject
531
532function OBJDEF:newArray(tbl)
533 return setmetatable(tbl or {}, isArray)
534end
535
536function OBJDEF:newObject(tbl)
537 return setmetatable(tbl or {}, isObject)
538end
539
540
541
542
543local function getnum(op)
544 return type(op) == 'number' and op or op.N
545end
546
547local isNumber = {
548 __tostring = function(T) return T.S end,
549 __unm = function(op) return getnum(op) end,
550
551 __concat = function(op1, op2) return tostring(op1) .. tostring(op2) end,
552 __add = function(op1, op2) return getnum(op1) + getnum(op2) end,
553 __sub = function(op1, op2) return getnum(op1) - getnum(op2) end,
554 __mul = function(op1, op2) return getnum(op1) * getnum(op2) end,
555 __div = function(op1, op2) return getnum(op1) / getnum(op2) end,
556 __mod = function(op1, op2) return getnum(op1) % getnum(op2) end,
557 __pow = function(op1, op2) return getnum(op1) ^ getnum(op2) end,
558 __lt = function(op1, op2) return getnum(op1) < getnum(op2) end,
559 __eq = function(op1, op2) return getnum(op1) == getnum(op2) end,
560 __le = function(op1, op2) return getnum(op1) <= getnum(op2) end,
561}
562isNumber.__index = isNumber
563
564function OBJDEF:asNumber(item)
565
566 if getmetatable(item) == isNumber then
567 -- it's already a JSON number object.
568 return item
569 elseif type(item) == 'table' and type(item.S) == 'string' and type(item.N) == 'number' then
570 -- it's a number-object table that lost its metatable, so give it one
571 return setmetatable(item, isNumber)
572 else
573 -- the normal situation... given a number or a string representation of a number....
574 local holder = {
575 S = tostring(item), -- S is the representation of the number as a string, which remains precise
576 N = tonumber(item), -- N is the number as a Lua number.
577 }
578 return setmetatable(holder, isNumber)
579 end
580end
581
582--
583-- Given an item that might be a normal string or number, or might be an 'isNumber' object defined above,
584-- return the string version. This shouldn't be needed often because the 'isNumber' object should autoconvert
585-- to a string in most cases, but it's here to allow it to be forced when needed.
586--
587function OBJDEF:forceString(item)
588 if type(item) == 'table' and type(item.S) == 'string' then
589 return item.S
590 else
591 return tostring(item)
592 end
593end
594
595--
596-- Given an item that might be a normal string or number, or might be an 'isNumber' object defined above,
597-- return the numeric version.
598--
599function OBJDEF:forceNumber(item)
600 if type(item) == 'table' and type(item.N) == 'number' then
601 return item.N
602 else
603 return tonumber(item)
604 end
605end
606
607
608local function unicode_codepoint_as_utf8(codepoint)
609 --
610 -- codepoint is a number
611 --
612 if codepoint <= 127 then
613 return string.char(codepoint)
614
615 elseif codepoint <= 2047 then
616 --
617 -- 110yyyxx 10xxxxxx <-- useful notation from http://en.wikipedia.org/wiki/Utf8
618 --
619 local highpart = math.floor(codepoint / 0x40)
620 local lowpart = codepoint - (0x40 * highpart)
621 return string.char(0xC0 + highpart,
622 0x80 + lowpart)
623
624 elseif codepoint <= 65535 then
625 --
626 -- 1110yyyy 10yyyyxx 10xxxxxx
627 --
628 local highpart = math.floor(codepoint / 0x1000)
629 local remainder = codepoint - 0x1000 * highpart
630 local midpart = math.floor(remainder / 0x40)
631 local lowpart = remainder - 0x40 * midpart
632
633 highpart = 0xE0 + highpart
634 midpart = 0x80 + midpart
635 lowpart = 0x80 + lowpart
636
637 --
638 -- Check for an invalid character (thanks Andy R. at Adobe).
639 -- See table 3.7, page 93, in http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf#G28070
640 --
641 if ( highpart == 0xE0 and midpart < 0xA0 ) or
642 ( highpart == 0xED and midpart > 0x9F ) or
643 ( highpart == 0xF0 and midpart < 0x90 ) or
644 ( highpart == 0xF4 and midpart > 0x8F )
645 then
646 return "?"
647 else
648 return string.char(highpart,
649 midpart,
650 lowpart)
651 end
652
653 else
654 --
655 -- 11110zzz 10zzyyyy 10yyyyxx 10xxxxxx
656 --
657 local highpart = math.floor(codepoint / 0x40000)
658 local remainder = codepoint - 0x40000 * highpart
659 local midA = math.floor(remainder / 0x1000)
660 remainder = remainder - 0x1000 * midA
661 local midB = math.floor(remainder / 0x40)
662 local lowpart = remainder - 0x40 * midB
663
664 return string.char(0xF0 + highpart,
665 0x80 + midA,
666 0x80 + midB,
667 0x80 + lowpart)
668 end
669end
670
671function OBJDEF:onDecodeError(message, text, location, etc)
672 if text then
673 if location then
674 message = string.format("%s at byte %d of: %s", message, location, text)
675 else
676 message = string.format("%s: %s", message, text)
677 end
678 end
679
680 if etc ~= nil then
681 message = message .. " (" .. OBJDEF:encode(etc) .. ")"
682 end
683
684 if self.assert then
685 self.assert(false, message)
686 else
687 assert(false, message)
688 end
689end
690
691function OBJDEF:onTrailingGarbage(json_text, location, parsed_value, etc)
692 return self:onDecodeError("trailing garbage", json_text, location, etc)
693end
694
695OBJDEF.onDecodeOfNilError = OBJDEF.onDecodeError
696OBJDEF.onDecodeOfHTMLError = OBJDEF.onDecodeError
697
698function OBJDEF:onEncodeError(message, etc)
699 if etc ~= nil then
700 message = message .. " (" .. OBJDEF:encode(etc) .. ")"
701 end
702
703 if self.assert then
704 self.assert(false, message)
705 else
706 assert(false, message)
707 end
708end
709
710local function grok_number(self, text, start, options)
711 --
712 -- Grab the integer part
713 --
714 local integer_part = text:match('^-?[1-9]%d*', start)
715 or text:match("^-?0", start)
716
717 if not integer_part then
718 self:onDecodeError("expected number", text, start, options.etc)
719 return nil, start -- in case the error method doesn't abort, return something sensible
720 end
721
722 local i = start + integer_part:len()
723
724 --
725 -- Grab an optional decimal part
726 --
727 local decimal_part = text:match('^%.%d+', i) or ""
728
729 i = i + decimal_part:len()
730
731 --
732 -- Grab an optional exponential part
733 --
734 local exponent_part = text:match('^[eE][-+]?%d+', i) or ""
735
736 i = i + exponent_part:len()
737
738 local full_number_text = integer_part .. decimal_part .. exponent_part
739
740 if options.decodeNumbersAsObjects then
741 return OBJDEF:asNumber(full_number_text), i
742 end
743
744 --
745 -- If we're told to stringify under certain conditions, so do.
746 -- We punt a bit when there's an exponent by just stringifying no matter what.
747 -- I suppose we should really look to see whether the exponent is actually big enough one
748 -- way or the other to trip stringification, but I'll be lazy about it until someone asks.
749 --
750 if (options.decodeIntegerStringificationLength
751 and
752 (integer_part:len() >= options.decodeIntegerStringificationLength or exponent_part:len() > 0))
753
754 or
755
756 (options.decodeDecimalStringificationLength
757 and
758 (decimal_part:len() >= options.decodeDecimalStringificationLength or exponent_part:len() > 0))
759 then
760 return full_number_text, i -- this returns the exact string representation seen in the original JSON
761 end
762
763
764
765 local as_number = tonumber(full_number_text)
766
767 if not as_number then
768 self:onDecodeError("bad number", text, start, options.etc)
769 return nil, start -- in case the error method doesn't abort, return something sensible
770 end
771
772 return as_number, i
773end
774
775
776local function grok_string(self, text, start, options)
777
778 if text:sub(start,start) ~= '"' then
779 self:onDecodeError("expected string's opening quote", text, start, options.etc)
780 return nil, start -- in case the error method doesn't abort, return something sensible
781 end
782
783 local i = start + 1 -- +1 to bypass the initial quote
784 local text_len = text:len()
785 local VALUE = ""
786 while i <= text_len do
787 local c = text:sub(i,i)
788 if c == '"' then
789 return VALUE, i + 1
790 end
791 if c ~= '\\' then
792 VALUE = VALUE .. c
793 i = i + 1
794 elseif text:match('^\\b', i) then
795 VALUE = VALUE .. "\b"
796 i = i + 2
797 elseif text:match('^\\f', i) then
798 VALUE = VALUE .. "\f"
799 i = i + 2
800 elseif text:match('^\\n', i) then
801 VALUE = VALUE .. "\n"
802 i = i + 2
803 elseif text:match('^\\r', i) then
804 VALUE = VALUE .. "\r"
805 i = i + 2
806 elseif text:match('^\\t', i) then
807 VALUE = VALUE .. "\t"
808 i = i + 2
809 else
810 local hex = text:match('^\\u([0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i)
811 if hex then
812 i = i + 6 -- bypass what we just read
813
814 -- We have a Unicode codepoint. It could be standalone, or if in the proper range and
815 -- followed by another in a specific range, it'll be a two-code surrogate pair.
816 local codepoint = tonumber(hex, 16)
817 if codepoint >= 0xD800 and codepoint <= 0xDBFF then
818 -- it's a hi surrogate... see whether we have a following low
819 local lo_surrogate = text:match('^\\u([dD][cdefCDEF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i)
820 if lo_surrogate then
821 i = i + 6 -- bypass the low surrogate we just read
822 codepoint = 0x2400 + (codepoint - 0xD800) * 0x400 + tonumber(lo_surrogate, 16)
823 else
824 -- not a proper low, so we'll just leave the first codepoint as is and spit it out.
825 end
826 end
827 VALUE = VALUE .. unicode_codepoint_as_utf8(codepoint)
828
829 else
830
831 -- just pass through what's escaped
832 VALUE = VALUE .. text:match('^\\(.)', i)
833 i = i + 2
834 end
835 end
836 end
837
838 self:onDecodeError("unclosed string", text, start, options.etc)
839 return nil, start -- in case the error method doesn't abort, return something sensible
840end
841
842local function skip_whitespace(text, start)
843
844 local _, match_end = text:find("^[ \n\r\t]+", start) -- [http://www.ietf.org/rfc/rfc4627.txt] Section 2
845 if match_end then
846 return match_end + 1
847 else
848 return start
849 end
850end
851
852local grok_one -- assigned later
853
854local function grok_object(self, text, start, options)
855
856 if text:sub(start,start) ~= '{' then
857 self:onDecodeError("expected '{'", text, start, options.etc)
858 return nil, start -- in case the error method doesn't abort, return something sensible
859 end
860
861 local i = skip_whitespace(text, start + 1) -- +1 to skip the '{'
862
863 local VALUE = self.strictTypes and self:newObject { } or { }
864
865 if text:sub(i,i) == '}' then
866 return VALUE, i + 1
867 end
868 local text_len = text:len()
869 while i <= text_len do
870 local key, new_i = grok_string(self, text, i, options)
871
872 i = skip_whitespace(text, new_i)
873
874 if text:sub(i, i) ~= ':' then
875 self:onDecodeError("expected colon", text, i, options.etc)
876 return nil, i -- in case the error method doesn't abort, return something sensible
877 end
878
879 i = skip_whitespace(text, i + 1)
880
881 local new_val, new_i = grok_one(self, text, i, options)
882
883 VALUE[key] = new_val
884
885 --
886 -- Expect now either '}' to end things, or a ',' to allow us to continue.
887 --
888 i = skip_whitespace(text, new_i)
889
890 local c = text:sub(i,i)
891
892 if c == '}' then
893 return VALUE, i + 1
894 end
895
896 if text:sub(i, i) ~= ',' then
897 self:onDecodeError("expected comma or '}'", text, i, options.etc)
898 return nil, i -- in case the error method doesn't abort, return something sensible
899 end
900
901 i = skip_whitespace(text, i + 1)
902 end
903
904 self:onDecodeError("unclosed '{'", text, start, options.etc)
905 return nil, start -- in case the error method doesn't abort, return something sensible
906end
907
908local function grok_array(self, text, start, options)
909 if text:sub(start,start) ~= '[' then
910 self:onDecodeError("expected '['", text, start, options.etc)
911 return nil, start -- in case the error method doesn't abort, return something sensible
912 end
913
914 local i = skip_whitespace(text, start + 1) -- +1 to skip the '['
915 local VALUE = self.strictTypes and self:newArray { } or { }
916 if text:sub(i,i) == ']' then
917 return VALUE, i + 1
918 end
919
920 local VALUE_INDEX = 1
921
922 local text_len = text:len()
923 while i <= text_len do
924 local val, new_i = grok_one(self, text, i, options)
925
926 -- can't table.insert(VALUE, val) here because it's a no-op if val is nil
927 VALUE[VALUE_INDEX] = val
928 VALUE_INDEX = VALUE_INDEX + 1
929
930 i = skip_whitespace(text, new_i)
931
932 --
933 -- Expect now either ']' to end things, or a ',' to allow us to continue.
934 --
935 local c = text:sub(i,i)
936 if c == ']' then
937 return VALUE, i + 1
938 end
939 if text:sub(i, i) ~= ',' then
940 self:onDecodeError("expected comma or ']'", text, i, options.etc)
941 return nil, i -- in case the error method doesn't abort, return something sensible
942 end
943 i = skip_whitespace(text, i + 1)
944 end
945 self:onDecodeError("unclosed '['", text, start, options.etc)
946 return nil, i -- in case the error method doesn't abort, return something sensible
947end
948
949
950grok_one = function(self, text, start, options)
951 -- Skip any whitespace
952 start = skip_whitespace(text, start)
953
954 if start > text:len() then
955 self:onDecodeError("unexpected end of string", text, nil, options.etc)
956 return nil, start -- in case the error method doesn't abort, return something sensible
957 end
958
959 if text:find('^"', start) then
960 return grok_string(self, text, start, options.etc)
961
962 elseif text:find('^[-0123456789 ]', start) then
963 return grok_number(self, text, start, options)
964
965 elseif text:find('^%{', start) then
966 return grok_object(self, text, start, options)
967
968 elseif text:find('^%[', start) then
969 return grok_array(self, text, start, options)
970
971 elseif text:find('^true', start) then
972 return true, start + 4
973
974 elseif text:find('^false', start) then
975 return false, start + 5
976
977 elseif text:find('^null', start) then
978 return nil, start + 4
979
980 else
981 self:onDecodeError("can't parse JSON", text, start, options.etc)
982 return nil, 1 -- in case the error method doesn't abort, return something sensible
983 end
984end
985
986function OBJDEF:decode(text, etc, options)
987 --
988 -- If the user didn't pass in a table of decode options, make an empty one.
989 --
990 if type(options) ~= 'table' then
991 options = {}
992 end
993
994 --
995 -- If they passed in an 'etc' argument, stuff it into the options.
996 -- (If not, any 'etc' field in the options they passed in remains to be used)
997 --
998 if etc ~= nil then
999 options.etc = etc
1000 end
1001
1002
1003 if type(self) ~= 'table' or self.__index ~= OBJDEF then
1004 local error_message = "JSON:decode must be called in method format"
1005 OBJDEF:onDecodeError(error_message, nil, nil, options.etc)
1006 return nil, error_message -- in case the error method doesn't abort, return something sensible
1007 end
1008
1009 if text == nil then
1010 local error_message = "nil passed to JSON:decode()"
1011 self:onDecodeOfNilError(error_message, nil, nil, options.etc)
1012 return nil, error_message -- in case the error method doesn't abort, return something sensible
1013
1014 elseif type(text) ~= 'string' then
1015 local error_message = "expected string argument to JSON:decode()"
1016 self:onDecodeError(string.format("%s, got %s", error_message, type(text)), nil, nil, options.etc)
1017 return nil, error_message -- in case the error method doesn't abort, return something sensible
1018 end
1019
1020 if text:match('^%s*$') then
1021 -- an empty string is nothing, but not an error
1022 return nil
1023 end
1024
1025 if text:match('^%s*<') then
1026 -- Can't be JSON... we'll assume it's HTML
1027 local error_message = "HTML passed to JSON:decode()"
1028 self:onDecodeOfHTMLError(error_message, text, nil, options.etc)
1029 return nil, error_message -- in case the error method doesn't abort, return something sensible
1030 end
1031
1032 --
1033 -- Ensure that it's not UTF-32 or UTF-16.
1034 -- Those are perfectly valid encodings for JSON (as per RFC 4627 section 3),
1035 -- but this package can't handle them.
1036 --
1037 if text:sub(1,1):byte() == 0 or (text:len() >= 2 and text:sub(2,2):byte() == 0) then
1038 local error_message = "JSON package groks only UTF-8, sorry"
1039 self:onDecodeError(error_message, text, nil, options.etc)
1040 return nil, error_message -- in case the error method doesn't abort, return something sensible
1041 end
1042
1043 --
1044 -- apply global options
1045 --
1046 if options.decodeNumbersAsObjects == nil then
1047 options.decodeNumbersAsObjects = self.decodeNumbersAsObjects
1048 end
1049 if options.decodeIntegerStringificationLength == nil then
1050 options.decodeIntegerStringificationLength = self.decodeIntegerStringificationLength
1051 end
1052 if options.decodeDecimalStringificationLength == nil then
1053 options.decodeDecimalStringificationLength = self.decodeDecimalStringificationLength
1054 end
1055
1056 --
1057 -- Finally, go parse it
1058 --
1059 local success, value, next_i = pcall(grok_one, self, text, 1, options)
1060
1061 if success then
1062
1063 local error_message = nil
1064 if next_i ~= #text + 1 then
1065 -- something's left over after we parsed the first thing.... whitespace is allowed.
1066 next_i = skip_whitespace(text, next_i)
1067
1068 -- if we have something left over now, it's trailing garbage
1069 if next_i ~= #text + 1 then
1070 value, error_message = self:onTrailingGarbage(text, next_i, value, options.etc)
1071 end
1072 end
1073 return value, error_message
1074
1075 else
1076
1077 -- If JSON:onDecodeError() didn't abort out of the pcall, we'll have received
1078 -- the error message here as "value", so pass it along as an assert.
1079 local error_message = value
1080 if self.assert then
1081 self.assert(false, error_message)
1082 else
1083 assert(false, error_message)
1084 end
1085 -- ...and if we're still here (because the assert didn't throw an error),
1086 -- return a nil and throw the error message on as a second arg
1087 return nil, error_message
1088
1089 end
1090end
1091
1092local function backslash_replacement_function(c)
1093 if c == "\n" then
1094 return "\\n"
1095 elseif c == "\r" then
1096 return "\\r"
1097 elseif c == "\t" then
1098 return "\\t"
1099 elseif c == "\b" then
1100 return "\\b"
1101 elseif c == "\f" then
1102 return "\\f"
1103 elseif c == '"' then
1104 return '\\"'
1105 elseif c == '\\' then
1106 return '\\\\'
1107 else
1108 return string.format("\\u%04x", c:byte())
1109 end
1110end
1111
1112local chars_to_be_escaped_in_JSON_string
1113 = '['
1114 .. '"' -- class sub-pattern to match a double quote
1115 .. '%\\' -- class sub-pattern to match a backslash
1116 .. '%z' -- class sub-pattern to match a null
1117 .. '\001' .. '-' .. '\031' -- class sub-pattern to match control characters
1118 .. ']'
1119
1120
1121local LINE_SEPARATOR_as_utf8 = unicode_codepoint_as_utf8(0x2028)
1122local PARAGRAPH_SEPARATOR_as_utf8 = unicode_codepoint_as_utf8(0x2029)
1123local function json_string_literal(value, options)
1124 local newval = value:gsub(chars_to_be_escaped_in_JSON_string, backslash_replacement_function)
1125 if options.stringsAreUtf8 then
1126 --
1127 -- This feels really ugly to just look into a string for the sequence of bytes that we know to be a particular utf8 character,
1128 -- but utf8 was designed purposefully to make this kind of thing possible. Still, feels dirty.
1129 -- I'd rather decode the byte stream into a character stream, but it's not technically needed so
1130 -- not technically worth it.
1131 --
1132 newval = newval:gsub(LINE_SEPARATOR_as_utf8, '\\u2028'):gsub(PARAGRAPH_SEPARATOR_as_utf8,'\\u2029')
1133 end
1134 return '"' .. newval .. '"'
1135end
1136
1137local function object_or_array(self, T, etc)
1138 --
1139 -- We need to inspect all the keys... if there are any strings, we'll convert to a JSON
1140 -- object. If there are only numbers, it's a JSON array.
1141 --
1142 -- If we'll be converting to a JSON object, we'll want to sort the keys so that the
1143 -- end result is deterministic.
1144 --
1145 local string_keys = { }
1146 local number_keys = { }
1147 local number_keys_must_be_strings = false
1148 local maximum_number_key
1149
1150 for key in pairs(T) do
1151 if type(key) == 'string' then
1152 table.insert(string_keys, key)
1153 elseif type(key) == 'number' then
1154 table.insert(number_keys, key)
1155 if key <= 0 or key >= math.huge then
1156 number_keys_must_be_strings = true
1157 elseif not maximum_number_key or key > maximum_number_key then
1158 maximum_number_key = key
1159 end
1160 else
1161 self:onEncodeError("can't encode table with a key of type " .. type(key), etc)
1162 end
1163 end
1164
1165 if #string_keys == 0 and not number_keys_must_be_strings then
1166 --
1167 -- An empty table, or a numeric-only array
1168 --
1169 if #number_keys > 0 then
1170 return nil, maximum_number_key -- an array
1171 elseif tostring(T) == "JSON array" then
1172 return nil
1173 elseif tostring(T) == "JSON object" then
1174 return { }
1175 else
1176 -- have to guess, so we'll pick array, since empty arrays are likely more common than empty objects
1177 return nil
1178 end
1179 end
1180
1181 table.sort(string_keys)
1182
1183 local map
1184 if #number_keys > 0 then
1185 --
1186 -- If we're here then we have either mixed string/number keys, or numbers inappropriate for a JSON array
1187 -- It's not ideal, but we'll turn the numbers into strings so that we can at least create a JSON object.
1188 --
1189
1190 if self.noKeyConversion then
1191 self:onEncodeError("a table with both numeric and string keys could be an object or array; aborting", etc)
1192 end
1193
1194 --
1195 -- Have to make a shallow copy of the source table so we can remap the numeric keys to be strings
1196 --
1197 map = { }
1198 for key, val in pairs(T) do
1199 map[key] = val
1200 end
1201
1202 table.sort(number_keys)
1203
1204 --
1205 -- Throw numeric keys in there as strings
1206 --
1207 for _, number_key in ipairs(number_keys) do
1208 local string_key = tostring(number_key)
1209 if map[string_key] == nil then
1210 table.insert(string_keys , string_key)
1211 map[string_key] = T[number_key]
1212 else
1213 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)
1214 end
1215 end
1216 end
1217
1218 return string_keys, nil, map
1219end
1220
1221--
1222-- Encode
1223--
1224-- 'options' is nil, or a table with possible keys:
1225--
1226-- pretty -- If true, return a pretty-printed version.
1227--
1228-- indent -- A string (usually of spaces) used to indent each nested level.
1229--
1230-- align_keys -- If true, align all the keys when formatting a table.
1231--
1232-- null -- If this exists with a string value, table elements with this value are output as JSON null.
1233--
1234-- stringsAreUtf8 -- If true, consider Lua strings not as a sequence of bytes, but as a sequence of UTF-8 characters.
1235-- (Currently, the only practical effect of setting this option is that Unicode LINE and PARAGRAPH
1236-- separators, if found in a string, are encoded with a JSON escape instead of as raw UTF-8.
1237-- The JSON is valid either way, but encoding this way, apparently, allows the resulting JSON
1238-- to also be valid Java.)
1239--
1240--
1241local encode_value -- must predeclare because it calls itself
1242function encode_value(self, value, parents, etc, options, indent, for_key)
1243
1244 --
1245 -- keys in a JSON object can never be null, so we don't even consider options.null when converting a key value
1246 --
1247 if value == nil or (not for_key and options and options.null and value == options.null) then
1248 return 'null'
1249
1250 elseif type(value) == 'string' then
1251 return json_string_literal(value, options)
1252
1253 elseif type(value) == 'number' then
1254 if value ~= value then
1255 --
1256 -- NaN (Not a Number).
1257 -- JSON has no NaN, so we have to fudge the best we can. This should really be a package option.
1258 --
1259 return "null"
1260 elseif value >= math.huge then
1261 --
1262 -- Positive infinity. JSON has no INF, so we have to fudge the best we can. This should
1263 -- really be a package option. Note: at least with some implementations, positive infinity
1264 -- is both ">= math.huge" and "<= -math.huge", which makes no sense but that's how it is.
1265 -- Negative infinity is properly "<= -math.huge". So, we must be sure to check the ">="
1266 -- case first.
1267 --
1268 return "1e+9999"
1269 elseif value <= -math.huge then
1270 --
1271 -- Negative infinity.
1272 -- JSON has no INF, so we have to fudge the best we can. This should really be a package option.
1273 --
1274 return "-1e+9999"
1275 else
1276 return tostring(value)
1277 end
1278
1279 elseif type(value) == 'boolean' then
1280 return tostring(value)
1281
1282 elseif type(value) ~= 'table' then
1283 self:onEncodeError("can't convert " .. type(value) .. " to JSON", etc)
1284
1285 elseif getmetatable(value) == isNumber then
1286 return tostring(value)
1287 else
1288 --
1289 -- A table to be converted to either a JSON object or array.
1290 --
1291 local T = value
1292
1293 if type(options) ~= 'table' then
1294 options = {}
1295 end
1296 if type(indent) ~= 'string' then
1297 indent = ""
1298 end
1299
1300 if parents[T] then
1301 self:onEncodeError("table " .. tostring(T) .. " is a child of itself", etc)
1302 else
1303 parents[T] = true
1304 end
1305
1306 local result_value
1307
1308 local object_keys, maximum_number_key, map = object_or_array(self, T, etc)
1309 if maximum_number_key then
1310 --
1311 -- An array...
1312 --
1313 local ITEMS = { }
1314 local key_indent = indent .. tostring(options.indent or "")
1315 for i = 1, maximum_number_key do
1316 if not options.array_newline then
1317 table.insert(ITEMS, encode_value(self, T[i], parents, etc, options, indent))
1318 else
1319 table.insert(ITEMS, encode_value(self, T[i], parents, etc, options, key_indent))
1320 end
1321 end
1322
1323 if options.pretty then
1324 if not options.array_newline then
1325 result_value = "[ " .. table.concat(ITEMS, ", ") .. " ]"
1326 else
1327 result_value = "[\n" .. key_indent .. table.concat(ITEMS, ",\n" .. key_indent) .. "\n" .. indent .. "]"
1328 end
1329 else
1330 result_value = "[" .. table.concat(ITEMS, ",") .. "]"
1331 end
1332
1333 elseif object_keys then
1334 --
1335 -- An object
1336 --
1337 local TT = map or T
1338
1339 if options.pretty then
1340
1341 local KEYS = { }
1342 local max_key_length = 0
1343 for _, key in ipairs(object_keys) do
1344 local encoded = encode_value(self, tostring(key), parents, etc, options, indent, true)
1345 if options.align_keys then
1346 max_key_length = math.max(max_key_length, #encoded)
1347 end
1348 table.insert(KEYS, encoded)
1349 end
1350 local key_indent = indent .. tostring(options.indent or "")
1351 local subtable_indent = key_indent .. string.rep(" ", max_key_length) .. (options.align_keys and " " or "")
1352 local FORMAT = "%s%" .. string.format("%d", max_key_length) .. "s: %s"
1353
1354 local COMBINED_PARTS = { }
1355 for i, key in ipairs(object_keys) do
1356 local encoded_val = encode_value(self, TT[key], parents, etc, options, subtable_indent)
1357 table.insert(COMBINED_PARTS, string.format(FORMAT, key_indent, KEYS[i], encoded_val))
1358 end
1359 result_value = "{\n" .. table.concat(COMBINED_PARTS, ",\n") .. "\n" .. indent .. "}"
1360
1361 else
1362
1363 local PARTS = { }
1364 for _, key in ipairs(object_keys) do
1365 local encoded_val = encode_value(self, TT[key], parents, etc, options, indent)
1366 local encoded_key = encode_value(self, tostring(key), parents, etc, options, indent, true)
1367 table.insert(PARTS, string.format("%s:%s", encoded_key, encoded_val))
1368 end
1369 result_value = "{" .. table.concat(PARTS, ",") .. "}"
1370
1371 end
1372 else
1373 --
1374 -- An empty array/object... we'll treat it as an array, though it should really be an option
1375 --
1376 result_value = "[]"
1377 end
1378
1379 parents[T] = false
1380 return result_value
1381 end
1382end
1383
1384local function top_level_encode(self, value, etc, options)
1385 local val = encode_value(self, value, {}, etc, options)
1386 if val == nil then
1387 --PRIVATE("may need to revert to the previous public verison if I can't figure out what the guy wanted")
1388 return val
1389 else
1390 return val
1391 end
1392end
1393
1394function OBJDEF:encode(value, etc, options)
1395 if type(self) ~= 'table' or self.__index ~= OBJDEF then
1396 OBJDEF:onEncodeError("JSON:encode must be called in method format", etc)
1397 end
1398
1399 --
1400 -- If the user didn't pass in a table of decode options, make an empty one.
1401 --
1402 if type(options) ~= 'table' then
1403 options = {}
1404 end
1405
1406 return top_level_encode(self, value, etc, options)
1407end
1408
1409function OBJDEF:encode_pretty(value, etc, options)
1410 if type(self) ~= 'table' or self.__index ~= OBJDEF then
1411 OBJDEF:onEncodeError("JSON:encode_pretty must be called in method format", etc)
1412 end
1413
1414 --
1415 -- If the user didn't pass in a table of decode options, use the default pretty ones
1416 --
1417 if type(options) ~= 'table' then
1418 options = default_pretty_options
1419 end
1420
1421 return top_level_encode(self, value, etc, options)
1422end
1423
1424function OBJDEF.__tostring()
1425 return "JSON encode/decode package"
1426end
1427
1428OBJDEF.__index = OBJDEF
1429
1430function OBJDEF:new(args)
1431 local new = { }
1432
1433 if args then
1434 for key, val in pairs(args) do
1435 new[key] = val
1436 end
1437 end
1438
1439 return setmetatable(new, OBJDEF)
1440end
1441
1442return OBJDEF:new()
1443
1444--
1445-- Version history:
1446--
1447-- 20161109.21 Oops, had a small boo-boo in the previous update.
1448--
1449-- 20161103.20 Used to silently ignore trailing garbage when decoding. Now fails via JSON:onTrailingGarbage()
1450-- http://seriot.ch/parsing_json.php
1451--
1452-- Built-in error message about "expected comma or ']'" had mistakenly referred to '['
1453--
1454-- Updated the built-in error reporting to refer to bytes rather than characters.
1455--
1456-- The decode() method no longer assumes that error handlers abort.
1457--
1458-- Made the VERSION string a string instead of a number
1459--
1460
1461-- 20160916.19 Fixed the isNumber.__index assignment (thanks to Jack Taylor)
1462--
1463-- 20160730.18 Added JSON:forceString() and JSON:forceNumber()
1464--
1465-- 20160728.17 Added concatenation to the metatable for JSON:asNumber()
1466--
1467-- 20160709.16 Could crash if not passed an options table (thanks jarno heikkinen <jarnoh@capturemonkey.com>).
1468--
1469-- Made JSON:asNumber() a bit more resilient to being passed the results of itself.
1470--
1471-- 20160526.15 Added the ability to easily encode null values in JSON, via the new "null" encoding option.
1472-- (Thanks to Adam B for bringing up the issue.)
1473--
1474-- Added some support for very large numbers and precise floats via
1475-- JSON.decodeNumbersAsObjects
1476-- JSON.decodeIntegerStringificationLength
1477-- JSON.decodeDecimalStringificationLength
1478--
1479-- Added the "stringsAreUtf8" encoding option. (Hat tip to http://lua-users.org/wiki/JsonModules )
1480--
1481-- 20141223.14 The encode_pretty() routine produced fine results for small datasets, but isn't really
1482-- appropriate for anything large, so with help from Alex Aulbach I've made the encode routines
1483-- more flexible, and changed the default encode_pretty() to be more generally useful.
1484--
1485-- Added a third 'options' argument to the encode() and encode_pretty() routines, to control
1486-- how the encoding takes place.
1487--
1488-- Updated docs to add assert() call to the loadfile() line, just as good practice so that
1489-- if there is a problem loading JSON.lua, the appropriate error message will percolate up.
1490--
1491-- 20140920.13 Put back (in a way that doesn't cause warnings about unused variables) the author string,
1492-- so that the source of the package, and its version number, are visible in compiled copies.
1493--
1494-- 20140911.12 Minor lua cleanup.
1495-- Fixed internal reference to 'JSON.noKeyConversion' to reference 'self' instead of 'JSON'.
1496-- (Thanks to SmugMug's David Parry for these.)
1497--
1498-- 20140418.11 JSON nulls embedded within an array were being ignored, such that
1499-- ["1",null,null,null,null,null,"seven"],
1500-- would return
1501-- {1,"seven"}
1502-- It's now fixed to properly return
1503-- {1, nil, nil, nil, nil, nil, "seven"}
1504-- Thanks to "haddock" for catching the error.
1505--
1506-- 20140116.10 The user's JSON.assert() wasn't always being used. Thanks to "blue" for the heads up.
1507--
1508-- 20131118.9 Update for Lua 5.3... it seems that tostring(2/1) produces "2.0" instead of "2",
1509-- and this caused some problems.
1510--
1511-- 20131031.8 Unified the code for encode() and encode_pretty(); they had been stupidly separate,
1512-- and had of course diverged (encode_pretty didn't get the fixes that encode got, so
1513-- sometimes produced incorrect results; thanks to Mattie for the heads up).
1514--
1515-- Handle encoding tables with non-positive numeric keys (unlikely, but possible).
1516--
1517-- If a table has both numeric and string keys, or its numeric keys are inappropriate
1518-- (such as being non-positive or infinite), the numeric keys are turned into
1519-- string keys appropriate for a JSON object. So, as before,
1520-- JSON:encode({ "one", "two", "three" })
1521-- produces the array
1522-- ["one","two","three"]
1523-- but now something with mixed key types like
1524-- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" }))
1525-- instead of throwing an error produces an object:
1526-- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"}
1527--
1528-- To maintain the prior throw-an-error semantics, set
1529-- JSON.noKeyConversion = true
1530--
1531-- 20131004.7 Release under a Creative Commons CC-BY license, which I should have done from day one, sorry.
1532--
1533-- 20130120.6 Comment update: added a link to the specific page on my blog where this code can
1534-- be found, so that folks who come across the code outside of my blog can find updates
1535-- more easily.
1536--
1537-- 20111207.5 Added support for the 'etc' arguments, for better error reporting.
1538--
1539-- 20110731.4 More feedback from David Kolf on how to make the tests for Nan/Infinity system independent.
1540--
1541-- 20110730.3 Incorporated feedback from David Kolf at http://lua-users.org/wiki/JsonModules:
1542--
1543-- * When encoding lua for JSON, Sparse numeric arrays are now handled by
1544-- spitting out full arrays, such that
1545-- JSON:encode({"one", "two", [10] = "ten"})
1546-- returns
1547-- ["one","two",null,null,null,null,null,null,null,"ten"]
1548--
1549-- In 20100810.2 and earlier, only up to the first non-null value would have been retained.
1550--
1551-- * When encoding lua for JSON, numeric value NaN gets spit out as null, and infinity as "1+e9999".
1552-- Version 20100810.2 and earlier created invalid JSON in both cases.
1553--
1554-- * Unicode surrogate pairs are now detected when decoding JSON.
1555--
1556-- 20100810.2 added some checking to ensure that an invalid Unicode character couldn't leak in to the UTF-8 encoding
1557--
1558-- 20100731.1 initial public release
1559--