· 9 years ago · May 20, 2017, 04:36 AM
1-- -*- coding: utf-8 -*-
2--
3-- Simple JSON encoding and decoding in pure Lua.
4--
5-- Copyright 2010-2017 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 = '20170416.23' -- version history at end of file
18local AUTHOR_NOTE = "-[ JSON.lua package by Jeffrey Friedl (http://regex.info/blog/lua/json) version 20170416.23 ]-"
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, -- turn pretty formatting on
201-- indent = " ", -- use this indent for each level of an array/object
202-- align_keys = false, -- if true, align the keys in a way that sounds like it should be nice, but is actually ugly
203-- array_newline = false, -- if true, array elements become one to a line rather than inline
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--
220--
221--
222-- PRETTY-PRINTING
223--
224-- Enabling the 'pretty' encode option helps generate human-readable JSON.
225--
226-- pretty = JSON:encode(val, etc, {
227-- pretty = true,
228-- indent = " ",
229-- align_keys = false,
230-- })
231--
232-- encode_pretty() is also provided: it's identical to encode() except
233-- that encode_pretty() provides a default options table if none given in the call:
234--
235-- { pretty = true, indent = " ", align_keys = false, array_newline = false }
236--
237-- For example, if
238--
239-- JSON:encode(data)
240--
241-- produces:
242--
243-- {"city":"Kyoto","climate":{"avg_temp":16,"humidity":"high","snowfall":"minimal"},"country":"Japan","wards":11}
244--
245-- then
246--
247-- JSON:encode_pretty(data)
248--
249-- produces:
250--
251-- {
252-- "city": "Kyoto",
253-- "climate": {
254-- "avg_temp": 16,
255-- "humidity": "high",
256-- "snowfall": "minimal"
257-- },
258-- "country": "Japan",
259-- "wards": 11
260-- }
261--
262-- The following lines all return identical strings:
263-- JSON:encode_pretty(data)
264-- JSON:encode_pretty(data, nil, { pretty = true, indent = " ", align_keys = false, array_newline = false})
265-- JSON:encode_pretty(data, nil, { pretty = true, indent = " " })
266-- JSON:encode (data, nil, { pretty = true, 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.
397--
398-- Consider the example above, with this option turned on:
399--
400-- JSON.decodeNumbersAsObjects = true
401--
402-- T = JSON:decode('{ "small":12345, "big":12345678901234567890123456789, "precise":9876.67890123456789012345 }')
403--
404-- print("small: ", type(T.small), T.small)
405-- print("big: ", type(T.big), T.big)
406-- print("precise: ", type(T.precise), T.precise)
407--
408-- This now produces:
409--
410-- small: table 12345
411-- big: table 12345678901234567890123456789
412-- precise: table 9876.67890123456789012345
413--
414-- However, within Lua you can still use the values (e.g. T.precise in the example above) in numeric
415-- contexts. In such cases you'll get the possibly-imprecise numeric version, but in string contexts
416-- and when the data finds its way to this package's encode() function, the original full-precision
417-- representation is used.
418--
419-- You can force access to the string or numeric version via
420-- JSON:forceString()
421-- JSON:forceNumber()
422-- For example,
423-- local probably_okay = JSON:forceNumber(T.small) -- 'probably_okay' is a number
424--
425-- Code the inspects the JSON-turned-Lua data using type() can run into troubles because what used to
426-- be a number can now be a table (e.g. as the small/big/precise example above shows). Update these
427-- situations to use JSON:isNumber(item), which returns nil if the item is neither a number nor one
428-- of these number objects. If it is either, it returns the number itself. For completeness there's
429-- also JSON:isString(item).
430--
431-- If you want to try to avoid the hassles of this "number as an object" kludge for all but really
432-- big numbers, you can set JSON.decodeNumbersAsObjects and then also set one or both of
433-- JSON:decodeIntegerObjectificationLength
434-- JSON:decodeDecimalObjectificationLength
435-- They refer to the length of the part of the number before and after a decimal point. If they are
436-- set and their part is at least that number of digits, objectification occurs. If both are set,
437-- objectification occurs when either length is met.
438--
439-- -----------------------
440--
441-- Even without using the JSON.decodeNumbersAsObjects option, you can encode numbers in your Lua
442-- table that retain high precision upon encoding to JSON, by using the JSON:asNumber() function:
443--
444-- T = {
445-- imprecise = 123456789123456789.123456789123456789,
446-- precise = JSON:asNumber("123456789123456789.123456789123456789")
447-- }
448--
449-- print(JSON:encode_pretty(T))
450--
451-- This produces:
452--
453-- {
454-- "precise": 123456789123456789.123456789123456789,
455-- "imprecise": 1.2345678912346e+17
456-- }
457--
458--
459-- -----------------------
460--
461-- A different way to handle big/precise JSON numbers is to have decode() merely return the exact
462-- string representation of the number instead of the number itself. This approach might be useful
463-- when the numbers are merely some kind of opaque object identifier and you want to work with them
464-- in Lua as strings anyway.
465--
466-- This approach is enabled by setting
467--
468-- JSON.decodeIntegerStringificationLength = 10
469--
470-- The value is the number of digits (of the integer part of the number) at which to stringify numbers.
471-- NOTE: this setting is ignored if JSON.decodeNumbersAsObjects is true, as that takes precedence.
472--
473-- Consider our previous example with this option set to 10:
474--
475-- JSON.decodeIntegerStringificationLength = 10
476--
477-- T = JSON:decode('{ "small":12345, "big":12345678901234567890123456789, "precise":9876.67890123456789012345 }')
478--
479-- print("small: ", type(T.small), T.small)
480-- print("big: ", type(T.big), T.big)
481-- print("precise: ", type(T.precise), T.precise)
482--
483-- This produces:
484--
485-- small: number 12345
486-- big: string 12345678901234567890123456789
487-- precise: number 9876.6789012346
488--
489-- The long integer of the 'big' field is at least JSON.decodeIntegerStringificationLength digits
490-- in length, so it's converted not to a Lua integer but to a Lua string. Using a value of 0 or 1 ensures
491-- that all JSON numeric data becomes strings in Lua.
492--
493-- Note that unlike
494-- JSON.decodeNumbersAsObjects = true
495-- this stringification is simple and unintelligent: the JSON number simply becomes a Lua string, and that's the end of it.
496-- If the string is then converted back to JSON, it's still a string. After running the code above, adding
497-- print(JSON:encode(T))
498-- produces
499-- {"big":"12345678901234567890123456789","precise":9876.6789012346,"small":12345}
500-- which is unlikely to be desired.
501--
502-- There's a comparable option for the length of the decimal part of a number:
503--
504-- JSON.decodeDecimalStringificationLength
505--
506-- This can be used alone or in conjunction with
507--
508-- JSON.decodeIntegerStringificationLength
509--
510-- to trip stringification on precise numbers with at least JSON.decodeIntegerStringificationLength digits after
511-- the decimal point. (Both are ignored if JSON.decodeNumbersAsObjects is true.)
512--
513-- This example:
514--
515-- JSON.decodeIntegerStringificationLength = 10
516-- JSON.decodeDecimalStringificationLength = 5
517--
518-- T = JSON:decode('{ "small":12345, "big":12345678901234567890123456789, "precise":9876.67890123456789012345 }')
519--
520-- print("small: ", type(T.small), T.small)
521-- print("big: ", type(T.big), T.big)
522-- print("precise: ", type(T.precise), T.precise)
523--
524-- produces:
525--
526-- small: number 12345
527-- big: string 12345678901234567890123456789
528-- precise: string 9876.67890123456789012345
529--
530--
531--
532--
533--
534-- SUMMARY OF METHODS YOU CAN OVERRIDE IN YOUR LOCAL LUA JSON OBJECT
535--
536-- assert
537-- onDecodeError
538-- onDecodeOfNilError
539-- onDecodeOfHTMLError
540-- onTrailingGarbage
541-- onEncodeError
542--
543-- If you want to create a separate Lua JSON object with its own error handlers,
544-- you can reload JSON.lua or use the :new() method.
545--
546---------------------------------------------------------------------------
547
548local default_pretty_indent = " "
549local default_pretty_options = { pretty = true, indent = default_pretty_indent, align_keys = false, array_newline = false }
550
551local isArray = { __tostring = function() return "JSON array" end } isArray.__index = isArray
552local isObject = { __tostring = function() return "JSON object" end } isObject.__index = isObject
553
554function OBJDEF:newArray(tbl)
555 return setmetatable(tbl or {}, isArray)
556end
557
558function OBJDEF:newObject(tbl)
559 return setmetatable(tbl or {}, isObject)
560end
561
562
563
564
565local function getnum(op)
566 return type(op) == 'number' and op or op.N
567end
568
569local isNumber = {
570 __tostring = function(T) return T.S end,
571 __unm = function(op) return getnum(op) end,
572
573 __concat = function(op1, op2) return tostring(op1) .. tostring(op2) end,
574 __add = function(op1, op2) return getnum(op1) + getnum(op2) end,
575 __sub = function(op1, op2) return getnum(op1) - getnum(op2) end,
576 __mul = function(op1, op2) return getnum(op1) * getnum(op2) end,
577 __div = function(op1, op2) return getnum(op1) / getnum(op2) end,
578 __mod = function(op1, op2) return getnum(op1) % getnum(op2) end,
579 __pow = function(op1, op2) return getnum(op1) ^ getnum(op2) end,
580 __lt = function(op1, op2) return getnum(op1) < getnum(op2) end,
581 __eq = function(op1, op2) return getnum(op1) == getnum(op2) end,
582 __le = function(op1, op2) return getnum(op1) <= getnum(op2) end,
583}
584isNumber.__index = isNumber
585
586function OBJDEF:asNumber(item)
587
588 if getmetatable(item) == isNumber then
589 -- it's already a JSON number object.
590 return item
591 elseif type(item) == 'table' and type(item.S) == 'string' and type(item.N) == 'number' then
592 -- it's a number-object table that lost its metatable, so give it one
593 return setmetatable(item, isNumber)
594 else
595 -- the normal situation... given a number or a string representation of a number....
596 local holder = {
597 S = tostring(item), -- S is the representation of the number as a string, which remains precise
598 N = tonumber(item), -- N is the number as a Lua number.
599 }
600 return setmetatable(holder, isNumber)
601 end
602end
603
604--
605-- Given an item that might be a normal string or number, or might be an 'isNumber' object defined above,
606-- return the string version. This shouldn't be needed often because the 'isNumber' object should autoconvert
607-- to a string in most cases, but it's here to allow it to be forced when needed.
608--
609function OBJDEF:forceString(item)
610 if type(item) == 'table' and type(item.S) == 'string' then
611 return item.S
612 else
613 return tostring(item)
614 end
615end
616
617--
618-- Given an item that might be a normal string or number, or might be an 'isNumber' object defined above,
619-- return the numeric version.
620--
621function OBJDEF:forceNumber(item)
622 if type(item) == 'table' and type(item.N) == 'number' then
623 return item.N
624 else
625 return tonumber(item)
626 end
627end
628
629--
630-- If the given item is a number, return it. Otherwise, return nil.
631-- This, this can be used both in a conditional and to access the number when you're not sure its form.
632--
633function OBJDEF:isNumber(item)
634 if type(item) == 'number' then
635 return item
636 elseif type(item) == 'table' and type(item.N) == 'number' then
637 return item.N
638 else
639 return nil
640 end
641end
642
643function OBJDEF:isString(item)
644 if type(item) == 'string' then
645 return item
646 elseif type(item) == 'table' and type(item.S) == 'string' then
647 return item.S
648 else
649 return nil
650 end
651end
652
653
654local function unicode_codepoint_as_utf8(codepoint)
655 --
656 -- codepoint is a number
657 --
658 if codepoint <= 127 then
659 return string.char(codepoint)
660
661 elseif codepoint <= 2047 then
662 --
663 -- 110yyyxx 10xxxxxx <-- useful notation from http://en.wikipedia.org/wiki/Utf8
664 --
665 local highpart = math.floor(codepoint / 0x40)
666 local lowpart = codepoint - (0x40 * highpart)
667 return string.char(0xC0 + highpart,
668 0x80 + lowpart)
669
670 elseif codepoint <= 65535 then
671 --
672 -- 1110yyyy 10yyyyxx 10xxxxxx
673 --
674 local highpart = math.floor(codepoint / 0x1000)
675 local remainder = codepoint - 0x1000 * highpart
676 local midpart = math.floor(remainder / 0x40)
677 local lowpart = remainder - 0x40 * midpart
678
679 highpart = 0xE0 + highpart
680 midpart = 0x80 + midpart
681 lowpart = 0x80 + lowpart
682
683 --
684 -- Check for an invalid character (thanks Andy R. at Adobe).
685 -- See table 3.7, page 93, in http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf#G28070
686 --
687 if ( highpart == 0xE0 and midpart < 0xA0 ) or
688 ( highpart == 0xED and midpart > 0x9F ) or
689 ( highpart == 0xF0 and midpart < 0x90 ) or
690 ( highpart == 0xF4 and midpart > 0x8F )
691 then
692 return "?"
693 else
694 return string.char(highpart,
695 midpart,
696 lowpart)
697 end
698
699 else
700 --
701 -- 11110zzz 10zzyyyy 10yyyyxx 10xxxxxx
702 --
703 local highpart = math.floor(codepoint / 0x40000)
704 local remainder = codepoint - 0x40000 * highpart
705 local midA = math.floor(remainder / 0x1000)
706 remainder = remainder - 0x1000 * midA
707 local midB = math.floor(remainder / 0x40)
708 local lowpart = remainder - 0x40 * midB
709
710 return string.char(0xF0 + highpart,
711 0x80 + midA,
712 0x80 + midB,
713 0x80 + lowpart)
714 end
715end
716
717function OBJDEF:onDecodeError(message, text, location, etc)
718 if text then
719 if location then
720 message = string.format("%s at byte %d of: %s", message, location, text)
721 else
722 message = string.format("%s: %s", message, text)
723 end
724 end
725
726 if etc ~= nil then
727 message = message .. " (" .. OBJDEF:encode(etc) .. ")"
728 end
729
730 if self.assert then
731 self.assert(false, message)
732 else
733 assert(false, message)
734 end
735end
736
737function OBJDEF:onTrailingGarbage(json_text, location, parsed_value, etc)
738 return self:onDecodeError("trailing garbage", json_text, location, etc)
739end
740
741OBJDEF.onDecodeOfNilError = OBJDEF.onDecodeError
742OBJDEF.onDecodeOfHTMLError = OBJDEF.onDecodeError
743
744function OBJDEF:onEncodeError(message, etc)
745 if etc ~= nil then
746 message = message .. " (" .. OBJDEF:encode(etc) .. ")"
747 end
748
749 if self.assert then
750 self.assert(false, message)
751 else
752 assert(false, message)
753 end
754end
755
756local function grok_number(self, text, start, options)
757 --
758 -- Grab the integer part
759 --
760 local integer_part = text:match('^-?[1-9]%d*', start)
761 or text:match("^-?0", start)
762
763 if not integer_part then
764 self:onDecodeError("expected number", text, start, options.etc)
765 return nil, start -- in case the error method doesn't abort, return something sensible
766 end
767
768 local i = start + integer_part:len()
769
770 --
771 -- Grab an optional decimal part
772 --
773 local decimal_part = text:match('^%.%d+', i) or ""
774
775 i = i + decimal_part:len()
776
777 --
778 -- Grab an optional exponential part
779 --
780 local exponent_part = text:match('^[eE][-+]?%d+', i) or ""
781
782 i = i + exponent_part:len()
783
784 local full_number_text = integer_part .. decimal_part .. exponent_part
785
786 if options.decodeNumbersAsObjects then
787
788 local objectify = false
789
790 if not options.decodeIntegerObjectificationLength and not options.decodeDecimalObjectificationLength then
791 -- no options, so objectify
792 objectify = true
793
794 elseif (options.decodeIntegerObjectificationLength
795 and
796 (integer_part:len() >= options.decodeIntegerObjectificationLength or exponent_part:len() > 0))
797
798 or
799 (options.decodeDecimalObjectificationLength
800 and
801 (decimal_part:len() >= options.decodeDecimalObjectificationLength or exponent_part:len() > 0))
802 then
803 -- have options and they are triggered, so objectify
804 objectify = true
805 end
806
807 if objectify then
808 return OBJDEF:asNumber(full_number_text), i
809 end
810 -- else, fall through to try to return as a straight-up number
811
812 else
813
814 -- Not always decoding numbers as objects, so perhaps encode as strings?
815
816 --
817 -- If we're told to stringify only under certain conditions, so do.
818 -- We punt a bit when there's an exponent by just stringifying no matter what.
819 -- I suppose we should really look to see whether the exponent is actually big enough one
820 -- way or the other to trip stringification, but I'll be lazy about it until someone asks.
821 --
822 if (options.decodeIntegerStringificationLength
823 and
824 (integer_part:len() >= options.decodeIntegerStringificationLength or exponent_part:len() > 0))
825
826 or
827
828 (options.decodeDecimalStringificationLength
829 and
830 (decimal_part:len() >= options.decodeDecimalStringificationLength or exponent_part:len() > 0))
831 then
832 return full_number_text, i -- this returns the exact string representation seen in the original JSON
833 end
834
835 end
836
837
838 local as_number = tonumber(full_number_text)
839
840 if not as_number then
841 self:onDecodeError("bad number", text, start, options.etc)
842 return nil, start -- in case the error method doesn't abort, return something sensible
843 end
844
845 return as_number, i
846end
847
848
849local function grok_string(self, text, start, options)
850
851 if text:sub(start,start) ~= '"' then
852 self:onDecodeError("expected string's opening quote", text, start, options.etc)
853 return nil, start -- in case the error method doesn't abort, return something sensible
854 end
855
856 local i = start + 1 -- +1 to bypass the initial quote
857 local text_len = text:len()
858 local VALUE = ""
859 while i <= text_len do
860 local c = text:sub(i,i)
861 if c == '"' then
862 return VALUE, i + 1
863 end
864 if c ~= '\\' then
865 VALUE = VALUE .. c
866 i = i + 1
867 elseif text:match('^\\b', i) then
868 VALUE = VALUE .. "\b"
869 i = i + 2
870 elseif text:match('^\\f', i) then
871 VALUE = VALUE .. "\f"
872 i = i + 2
873 elseif text:match('^\\n', i) then
874 VALUE = VALUE .. "\n"
875 i = i + 2
876 elseif text:match('^\\r', i) then
877 VALUE = VALUE .. "\r"
878 i = i + 2
879 elseif text:match('^\\t', i) then
880 VALUE = VALUE .. "\t"
881 i = i + 2
882 else
883 local hex = text:match('^\\u([0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i)
884 if hex then
885 i = i + 6 -- bypass what we just read
886
887 -- We have a Unicode codepoint. It could be standalone, or if in the proper range and
888 -- followed by another in a specific range, it'll be a two-code surrogate pair.
889 local codepoint = tonumber(hex, 16)
890 if codepoint >= 0xD800 and codepoint <= 0xDBFF then
891 -- it's a hi surrogate... see whether we have a following low
892 local lo_surrogate = text:match('^\\u([dD][cdefCDEF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i)
893 if lo_surrogate then
894 i = i + 6 -- bypass the low surrogate we just read
895 codepoint = 0x2400 + (codepoint - 0xD800) * 0x400 + tonumber(lo_surrogate, 16)
896 else
897 -- not a proper low, so we'll just leave the first codepoint as is and spit it out.
898 end
899 end
900 VALUE = VALUE .. unicode_codepoint_as_utf8(codepoint)
901
902 else
903
904 -- just pass through what's escaped
905 VALUE = VALUE .. text:match('^\\(.)', i)
906 i = i + 2
907 end
908 end
909 end
910
911 self:onDecodeError("unclosed string", text, start, options.etc)
912 return nil, start -- in case the error method doesn't abort, return something sensible
913end
914
915local function skip_whitespace(text, start)
916
917 local _, match_end = text:find("^[ \n\r\t]+", start) -- [http://www.ietf.org/rfc/rfc4627.txt] Section 2
918 if match_end then
919 return match_end + 1
920 else
921 return start
922 end
923end
924
925local grok_one -- assigned later
926
927local function grok_object(self, text, start, options)
928
929 if text:sub(start,start) ~= '{' then
930 self:onDecodeError("expected '{'", text, start, options.etc)
931 return nil, start -- in case the error method doesn't abort, return something sensible
932 end
933
934 local i = skip_whitespace(text, start + 1) -- +1 to skip the '{'
935
936 local VALUE = self.strictTypes and self:newObject { } or { }
937
938 if text:sub(i,i) == '}' then
939 return VALUE, i + 1
940 end
941 local text_len = text:len()
942 while i <= text_len do
943 local key, new_i = grok_string(self, text, i, options)
944
945 i = skip_whitespace(text, new_i)
946
947 if text:sub(i, i) ~= ':' then
948 self:onDecodeError("expected colon", text, i, options.etc)
949 return nil, i -- in case the error method doesn't abort, return something sensible
950 end
951
952 i = skip_whitespace(text, i + 1)
953
954 local new_val, new_i = grok_one(self, text, i, options)
955
956 VALUE[key] = new_val
957
958 --
959 -- Expect now either '}' to end things, or a ',' to allow us to continue.
960 --
961 i = skip_whitespace(text, new_i)
962
963 local c = text:sub(i,i)
964
965 if c == '}' then
966 return VALUE, i + 1
967 end
968
969 if text:sub(i, i) ~= ',' then
970 self:onDecodeError("expected comma or '}'", text, i, options.etc)
971 return nil, i -- in case the error method doesn't abort, return something sensible
972 end
973
974 i = skip_whitespace(text, i + 1)
975 end
976
977 self:onDecodeError("unclosed '{'", text, start, options.etc)
978 return nil, start -- in case the error method doesn't abort, return something sensible
979end
980
981local function grok_array(self, text, start, options)
982 if text:sub(start,start) ~= '[' then
983 self:onDecodeError("expected '['", text, start, options.etc)
984 return nil, start -- in case the error method doesn't abort, return something sensible
985 end
986
987 local i = skip_whitespace(text, start + 1) -- +1 to skip the '['
988 local VALUE = self.strictTypes and self:newArray { } or { }
989 if text:sub(i,i) == ']' then
990 return VALUE, i + 1
991 end
992
993 local VALUE_INDEX = 1
994
995 local text_len = text:len()
996 while i <= text_len do
997 local val, new_i = grok_one(self, text, i, options)
998
999 -- can't table.insert(VALUE, val) here because it's a no-op if val is nil
1000 VALUE[VALUE_INDEX] = val
1001 VALUE_INDEX = VALUE_INDEX + 1
1002
1003 i = skip_whitespace(text, new_i)
1004
1005 --
1006 -- Expect now either ']' to end things, or a ',' to allow us to continue.
1007 --
1008 local c = text:sub(i,i)
1009 if c == ']' then
1010 return VALUE, i + 1
1011 end
1012 if text:sub(i, i) ~= ',' then
1013 self:onDecodeError("expected comma or ']'", text, i, options.etc)
1014 return nil, i -- in case the error method doesn't abort, return something sensible
1015 end
1016 i = skip_whitespace(text, i + 1)
1017 end
1018 self:onDecodeError("unclosed '['", text, start, options.etc)
1019 return nil, i -- in case the error method doesn't abort, return something sensible
1020end
1021
1022
1023grok_one = function(self, text, start, options)
1024 -- Skip any whitespace
1025 start = skip_whitespace(text, start)
1026
1027 if start > text:len() then
1028 self:onDecodeError("unexpected end of string", text, nil, options.etc)
1029 return nil, start -- in case the error method doesn't abort, return something sensible
1030 end
1031
1032 if text:find('^"', start) then
1033 return grok_string(self, text, start, options.etc)
1034
1035 elseif text:find('^[-0123456789 ]', start) then
1036 return grok_number(self, text, start, options)
1037
1038 elseif text:find('^%{', start) then
1039 return grok_object(self, text, start, options)
1040
1041 elseif text:find('^%[', start) then
1042 return grok_array(self, text, start, options)
1043
1044 elseif text:find('^true', start) then
1045 return true, start + 4
1046
1047 elseif text:find('^false', start) then
1048 return false, start + 5
1049
1050 elseif text:find('^null', start) then
1051 return nil, start + 4
1052
1053 else
1054 self:onDecodeError("can't parse JSON", text, start, options.etc)
1055 return nil, 1 -- in case the error method doesn't abort, return something sensible
1056 end
1057end
1058
1059function OBJDEF:decode(text, etc, options)
1060 --
1061 -- If the user didn't pass in a table of decode options, make an empty one.
1062 --
1063 if type(options) ~= 'table' then
1064 options = {}
1065 end
1066
1067 --
1068 -- If they passed in an 'etc' argument, stuff it into the options.
1069 -- (If not, any 'etc' field in the options they passed in remains to be used)
1070 --
1071 if etc ~= nil then
1072 options.etc = etc
1073 end
1074
1075
1076 if type(self) ~= 'table' or self.__index ~= OBJDEF then
1077 local error_message = "JSON:decode must be called in method format"
1078 OBJDEF:onDecodeError(error_message, nil, nil, options.etc)
1079 return nil, error_message -- in case the error method doesn't abort, return something sensible
1080 end
1081
1082 if text == nil then
1083 local error_message = "nil passed to JSON:decode()"
1084 self:onDecodeOfNilError(error_message, nil, nil, options.etc)
1085 return nil, error_message -- in case the error method doesn't abort, return something sensible
1086
1087 elseif type(text) ~= 'string' then
1088 local error_message = "expected string argument to JSON:decode()"
1089 self:onDecodeError(string.format("%s, got %s", error_message, type(text)), nil, nil, options.etc)
1090 return nil, error_message -- in case the error method doesn't abort, return something sensible
1091 end
1092
1093 if text:match('^%s*$') then
1094 -- an empty string is nothing, but not an error
1095 return nil
1096 end
1097
1098 if text:match('^%s*<') then
1099 -- Can't be JSON... we'll assume it's HTML
1100 local error_message = "HTML passed to JSON:decode()"
1101 self:onDecodeOfHTMLError(error_message, text, nil, options.etc)
1102 return nil, error_message -- in case the error method doesn't abort, return something sensible
1103 end
1104
1105 --
1106 -- Ensure that it's not UTF-32 or UTF-16.
1107 -- Those are perfectly valid encodings for JSON (as per RFC 4627 section 3),
1108 -- but this package can't handle them.
1109 --
1110 if text:sub(1,1):byte() == 0 or (text:len() >= 2 and text:sub(2,2):byte() == 0) then
1111 local error_message = "JSON package groks only UTF-8, sorry"
1112 self:onDecodeError(error_message, text, nil, options.etc)
1113 return nil, error_message -- in case the error method doesn't abort, return something sensible
1114 end
1115
1116 --
1117 -- apply global options
1118 --
1119 if options.decodeNumbersAsObjects == nil then
1120 options.decodeNumbersAsObjects = self.decodeNumbersAsObjects
1121 end
1122 if options.decodeIntegerObjectificationLength == nil then
1123 options.decodeIntegerObjectificationLength = self.decodeIntegerObjectificationLength
1124 end
1125 if options.decodeDecimalObjectificationLength == nil then
1126 options.decodeDecimalObjectificationLength = self.decodeDecimalObjectificationLength
1127 end
1128 if options.decodeIntegerStringificationLength == nil then
1129 options.decodeIntegerStringificationLength = self.decodeIntegerStringificationLength
1130 end
1131 if options.decodeDecimalStringificationLength == nil then
1132 options.decodeDecimalStringificationLength = self.decodeDecimalStringificationLength
1133 end
1134
1135
1136 --
1137 -- Finally, go parse it
1138 --
1139 local success, value, next_i = pcall(grok_one, self, text, 1, options)
1140
1141 if success then
1142
1143 local error_message = nil
1144 if next_i ~= #text + 1 then
1145 -- something's left over after we parsed the first thing.... whitespace is allowed.
1146 next_i = skip_whitespace(text, next_i)
1147
1148 -- if we have something left over now, it's trailing garbage
1149 if next_i ~= #text + 1 then
1150 value, error_message = self:onTrailingGarbage(text, next_i, value, options.etc)
1151 end
1152 end
1153 return value, error_message
1154
1155 else
1156
1157 -- If JSON:onDecodeError() didn't abort out of the pcall, we'll have received
1158 -- the error message here as "value", so pass it along as an assert.
1159 local error_message = value
1160 if self.assert then
1161 self.assert(false, error_message)
1162 else
1163 assert(false, error_message)
1164 end
1165 -- ...and if we're still here (because the assert didn't throw an error),
1166 -- return a nil and throw the error message on as a second arg
1167 return nil, error_message
1168
1169 end
1170end
1171
1172local function backslash_replacement_function(c)
1173 if c == "\n" then
1174 return "\\n"
1175 elseif c == "\r" then
1176 return "\\r"
1177 elseif c == "\t" then
1178 return "\\t"
1179 elseif c == "\b" then
1180 return "\\b"
1181 elseif c == "\f" then
1182 return "\\f"
1183 elseif c == '"' then
1184 return '\\"'
1185 elseif c == '\\' then
1186 return '\\\\'
1187 else
1188 return string.format("\\u%04x", c:byte())
1189 end
1190end
1191
1192local chars_to_be_escaped_in_JSON_string
1193 = '['
1194 .. '"' -- class sub-pattern to match a double quote
1195 .. '%\\' -- class sub-pattern to match a backslash
1196 .. '%z' -- class sub-pattern to match a null
1197 .. '\001' .. '-' .. '\031' -- class sub-pattern to match control characters
1198 .. ']'
1199
1200
1201local LINE_SEPARATOR_as_utf8 = unicode_codepoint_as_utf8(0x2028)
1202local PARAGRAPH_SEPARATOR_as_utf8 = unicode_codepoint_as_utf8(0x2029)
1203local function json_string_literal(value, options)
1204 local newval = value:gsub(chars_to_be_escaped_in_JSON_string, backslash_replacement_function)
1205 if options.stringsAreUtf8 then
1206 --
1207 -- This feels really ugly to just look into a string for the sequence of bytes that we know to be a particular utf8 character,
1208 -- but utf8 was designed purposefully to make this kind of thing possible. Still, feels dirty.
1209 -- I'd rather decode the byte stream into a character stream, but it's not technically needed so
1210 -- not technically worth it.
1211 --
1212 newval = newval:gsub(LINE_SEPARATOR_as_utf8, '\\u2028'):gsub(PARAGRAPH_SEPARATOR_as_utf8,'\\u2029')
1213 end
1214 return '"' .. newval .. '"'
1215end
1216
1217local function object_or_array(self, T, etc)
1218 --
1219 -- We need to inspect all the keys... if there are any strings, we'll convert to a JSON
1220 -- object. If there are only numbers, it's a JSON array.
1221 --
1222 -- If we'll be converting to a JSON object, we'll want to sort the keys so that the
1223 -- end result is deterministic.
1224 --
1225 local string_keys = { }
1226 local number_keys = { }
1227 local number_keys_must_be_strings = false
1228 local maximum_number_key
1229
1230 for key in pairs(T) do
1231 if type(key) == 'string' then
1232 table.insert(string_keys, key)
1233 elseif type(key) == 'number' then
1234 table.insert(number_keys, key)
1235 if key <= 0 or key >= math.huge then
1236 number_keys_must_be_strings = true
1237 elseif not maximum_number_key or key > maximum_number_key then
1238 maximum_number_key = key
1239 end
1240 else
1241 self:onEncodeError("can't encode table with a key of type " .. type(key), etc)
1242 end
1243 end
1244
1245 if #string_keys == 0 and not number_keys_must_be_strings then
1246 --
1247 -- An empty table, or a numeric-only array
1248 --
1249 if #number_keys > 0 then
1250 return nil, maximum_number_key -- an array
1251 elseif tostring(T) == "JSON array" then
1252 return nil
1253 elseif tostring(T) == "JSON object" then
1254 return { }
1255 else
1256 -- have to guess, so we'll pick array, since empty arrays are likely more common than empty objects
1257 return nil
1258 end
1259 end
1260
1261 table.sort(string_keys)
1262
1263 local map
1264 if #number_keys > 0 then
1265 --
1266 -- If we're here then we have either mixed string/number keys, or numbers inappropriate for a JSON array
1267 -- It's not ideal, but we'll turn the numbers into strings so that we can at least create a JSON object.
1268 --
1269
1270 if self.noKeyConversion then
1271 self:onEncodeError("a table with both numeric and string keys could be an object or array; aborting", etc)
1272 end
1273
1274 --
1275 -- Have to make a shallow copy of the source table so we can remap the numeric keys to be strings
1276 --
1277 map = { }
1278 for key, val in pairs(T) do
1279 map[key] = val
1280 end
1281
1282 table.sort(number_keys)
1283
1284 --
1285 -- Throw numeric keys in there as strings
1286 --
1287 for _, number_key in ipairs(number_keys) do
1288 local string_key = tostring(number_key)
1289 if map[string_key] == nil then
1290 table.insert(string_keys , string_key)
1291 map[string_key] = T[number_key]
1292 else
1293 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)
1294 end
1295 end
1296 end
1297
1298 return string_keys, nil, map
1299end
1300
1301--
1302-- Encode
1303--
1304-- 'options' is nil, or a table with possible keys:
1305--
1306-- pretty -- If true, return a pretty-printed version.
1307--
1308-- indent -- A string (usually of spaces) used to indent each nested level.
1309--
1310-- align_keys -- If true, align all the keys when formatting a table. The result is uglier than one might at first imagine.
1311-- Results are undefined if 'align_keys' is true but 'pretty' is not.
1312--
1313-- array_newline -- If true, array elements are formatted each to their own line. The default is to all fall inline.
1314-- Results are undefined if 'array_newline' is true but 'pretty' is not.
1315--
1316-- null -- If this exists with a string value, table elements with this value are output as JSON null.
1317--
1318-- stringsAreUtf8 -- If true, consider Lua strings not as a sequence of bytes, but as a sequence of UTF-8 characters.
1319-- (Currently, the only practical effect of setting this option is that Unicode LINE and PARAGRAPH
1320-- separators, if found in a string, are encoded with a JSON escape instead of as raw UTF-8.
1321-- The JSON is valid either way, but encoding this way, apparently, allows the resulting JSON
1322-- to also be valid Java.)
1323--
1324--
1325local encode_value -- must predeclare because it calls itself
1326function encode_value(self, value, parents, etc, options, indent, for_key)
1327
1328 --
1329 -- keys in a JSON object can never be null, so we don't even consider options.null when converting a key value
1330 --
1331 if value == nil or (not for_key and options and options.null and value == options.null) then
1332 return 'null'
1333
1334 elseif type(value) == 'string' then
1335 return json_string_literal(value, options)
1336
1337 elseif type(value) == 'number' then
1338 if value ~= value then
1339 --
1340 -- NaN (Not a Number).
1341 -- JSON has no NaN, so we have to fudge the best we can. This should really be a package option.
1342 --
1343 return "null"
1344 elseif value >= math.huge then
1345 --
1346 -- Positive infinity. JSON has no INF, so we have to fudge the best we can. This should
1347 -- really be a package option. Note: at least with some implementations, positive infinity
1348 -- is both ">= math.huge" and "<= -math.huge", which makes no sense but that's how it is.
1349 -- Negative infinity is properly "<= -math.huge". So, we must be sure to check the ">="
1350 -- case first.
1351 --
1352 return "1e+9999"
1353 elseif value <= -math.huge then
1354 --
1355 -- Negative infinity.
1356 -- JSON has no INF, so we have to fudge the best we can. This should really be a package option.
1357 --
1358 return "-1e+9999"
1359 else
1360 return tostring(value)
1361 end
1362
1363 elseif type(value) == 'boolean' then
1364 return tostring(value)
1365
1366 elseif type(value) ~= 'table' then
1367 self:onEncodeError("can't convert " .. type(value) .. " to JSON", etc)
1368
1369 elseif getmetatable(value) == isNumber then
1370 return tostring(value)
1371 else
1372 --
1373 -- A table to be converted to either a JSON object or array.
1374 --
1375 local T = value
1376
1377 if type(options) ~= 'table' then
1378 options = {}
1379 end
1380 if type(indent) ~= 'string' then
1381 indent = ""
1382 end
1383
1384 if parents[T] then
1385 self:onEncodeError("table " .. tostring(T) .. " is a child of itself", etc)
1386 else
1387 parents[T] = true
1388 end
1389
1390 local result_value
1391
1392 local object_keys, maximum_number_key, map = object_or_array(self, T, etc)
1393 if maximum_number_key then
1394 --
1395 -- An array...
1396 --
1397 local key_indent
1398 if options.array_newline then
1399 key_indent = indent .. tostring(options.indent or "")
1400 else
1401 key_indent = indent
1402 end
1403
1404 local ITEMS = { }
1405 for i = 1, maximum_number_key do
1406 table.insert(ITEMS, encode_value(self, T[i], parents, etc, options, key_indent))
1407 end
1408
1409 if options.array_newline then
1410 result_value = "[\n" .. key_indent .. table.concat(ITEMS, ",\n" .. key_indent) .. "\n" .. indent .. "]"
1411 elseif options.pretty then
1412 result_value = "[ " .. table.concat(ITEMS, ", ") .. " ]"
1413 else
1414 result_value = "[" .. table.concat(ITEMS, ",") .. "]"
1415 end
1416
1417 elseif object_keys then
1418 --
1419 -- An object
1420 --
1421 local TT = map or T
1422
1423 if options.pretty then
1424
1425 local KEYS = { }
1426 local max_key_length = 0
1427 for _, key in ipairs(object_keys) do
1428 local encoded = encode_value(self, tostring(key), parents, etc, options, indent, true)
1429 if options.align_keys then
1430 max_key_length = math.max(max_key_length, #encoded)
1431 end
1432 table.insert(KEYS, encoded)
1433 end
1434 local key_indent = indent .. tostring(options.indent or "")
1435 local subtable_indent = key_indent .. string.rep(" ", max_key_length) .. (options.align_keys and " " or "")
1436 local FORMAT = "%s%" .. string.format("%d", max_key_length) .. "s: %s"
1437
1438 local COMBINED_PARTS = { }
1439 for i, key in ipairs(object_keys) do
1440 local encoded_val = encode_value(self, TT[key], parents, etc, options, subtable_indent)
1441 table.insert(COMBINED_PARTS, string.format(FORMAT, key_indent, KEYS[i], encoded_val))
1442 end
1443 result_value = "{\n" .. table.concat(COMBINED_PARTS, ",\n") .. "\n" .. indent .. "}"
1444
1445 else
1446
1447 local PARTS = { }
1448 for _, key in ipairs(object_keys) do
1449 local encoded_val = encode_value(self, TT[key], parents, etc, options, indent)
1450 local encoded_key = encode_value(self, tostring(key), parents, etc, options, indent, true)
1451 table.insert(PARTS, string.format("%s:%s", encoded_key, encoded_val))
1452 end
1453 result_value = "{" .. table.concat(PARTS, ",") .. "}"
1454
1455 end
1456 else
1457 --
1458 -- An empty array/object... we'll treat it as an array, though it should really be an option
1459 --
1460 result_value = "[]"
1461 end
1462
1463 parents[T] = false
1464 return result_value
1465 end
1466end
1467
1468local function top_level_encode(self, value, etc, options)
1469 local val = encode_value(self, value, {}, etc, options)
1470 if val == nil then
1471 --PRIVATE("may need to revert to the previous public verison if I can't figure out what the guy wanted")
1472 return val
1473 else
1474 return val
1475 end
1476end
1477
1478function OBJDEF:encode(value, etc, options)
1479 if type(self) ~= 'table' or self.__index ~= OBJDEF then
1480 OBJDEF:onEncodeError("JSON:encode must be called in method format", etc)
1481 end
1482
1483 --
1484 -- If the user didn't pass in a table of decode options, make an empty one.
1485 --
1486 if type(options) ~= 'table' then
1487 options = {}
1488 end
1489
1490 return top_level_encode(self, value, etc, options)
1491end
1492
1493function OBJDEF:encode_pretty(value, etc, options)
1494 if type(self) ~= 'table' or self.__index ~= OBJDEF then
1495 OBJDEF:onEncodeError("JSON:encode_pretty must be called in method format", etc)
1496 end
1497
1498 --
1499 -- If the user didn't pass in a table of decode options, use the default pretty ones
1500 --
1501 if type(options) ~= 'table' then
1502 options = default_pretty_options
1503 end
1504
1505 return top_level_encode(self, value, etc, options)
1506end
1507
1508function OBJDEF.__tostring()
1509 return "JSON encode/decode package"
1510end
1511
1512OBJDEF.__index = OBJDEF
1513
1514function OBJDEF:new(args)
1515 local new = { }
1516
1517 if args then
1518 for key, val in pairs(args) do
1519 new[key] = val
1520 end
1521 end
1522
1523 return setmetatable(new, OBJDEF)
1524end
1525
1526return OBJDEF:new()
1527
1528--
1529-- Version history:
1530--
1531-- 20170416.23 Added the "array_newline" formatting option suggested by yurenchen (http://www.yurenchen.com/)
1532--
1533-- 20161128.22 Added:
1534-- JSON:isString()
1535-- JSON:isNumber()
1536-- JSON:decodeIntegerObjectificationLength
1537-- JSON:decodeDecimalObjectificationLength
1538--
1539-- 20161109.21 Oops, had a small boo-boo in the previous update.
1540--
1541-- 20161103.20 Used to silently ignore trailing garbage when decoding. Now fails via JSON:onTrailingGarbage()
1542-- http://seriot.ch/parsing_json.php
1543--
1544-- Built-in error message about "expected comma or ']'" had mistakenly referred to '['
1545--
1546-- Updated the built-in error reporting to refer to bytes rather than characters.
1547--
1548-- The decode() method no longer assumes that error handlers abort.
1549--
1550-- Made the VERSION string a string instead of a number
1551--
1552
1553-- 20160916.19 Fixed the isNumber.__index assignment (thanks to Jack Taylor)
1554--
1555-- 20160730.18 Added JSON:forceString() and JSON:forceNumber()
1556--
1557-- 20160728.17 Added concatenation to the metatable for JSON:asNumber()
1558--
1559-- 20160709.16 Could crash if not passed an options table (thanks jarno heikkinen <jarnoh@capturemonkey.com>).
1560--
1561-- Made JSON:asNumber() a bit more resilient to being passed the results of itself.
1562--
1563-- 20160526.15 Added the ability to easily encode null values in JSON, via the new "null" encoding option.
1564-- (Thanks to Adam B for bringing up the issue.)
1565--
1566-- Added some support for very large numbers and precise floats via
1567-- JSON.decodeNumbersAsObjects
1568-- JSON.decodeIntegerStringificationLength
1569-- JSON.decodeDecimalStringificationLength
1570--
1571-- Added the "stringsAreUtf8" encoding option. (Hat tip to http://lua-users.org/wiki/JsonModules )
1572--
1573-- 20141223.14 The encode_pretty() routine produced fine results for small datasets, but isn't really
1574-- appropriate for anything large, so with help from Alex Aulbach I've made the encode routines
1575-- more flexible, and changed the default encode_pretty() to be more generally useful.
1576--
1577-- Added a third 'options' argument to the encode() and encode_pretty() routines, to control
1578-- how the encoding takes place.
1579--
1580-- Updated docs to add assert() call to the loadfile() line, just as good practice so that
1581-- if there is a problem loading JSON.lua, the appropriate error message will percolate up.
1582--
1583-- 20140920.13 Put back (in a way that doesn't cause warnings about unused variables) the author string,
1584-- so that the source of the package, and its version number, are visible in compiled copies.
1585--
1586-- 20140911.12 Minor lua cleanup.
1587-- Fixed internal reference to 'JSON.noKeyConversion' to reference 'self' instead of 'JSON'.
1588-- (Thanks to SmugMug's David Parry for these.)
1589--
1590-- 20140418.11 JSON nulls embedded within an array were being ignored, such that
1591-- ["1",null,null,null,null,null,"seven"],
1592-- would return
1593-- {1,"seven"}
1594-- It's now fixed to properly return
1595-- {1, nil, nil, nil, nil, nil, "seven"}
1596-- Thanks to "haddock" for catching the error.
1597--
1598-- 20140116.10 The user's JSON.assert() wasn't always being used. Thanks to "blue" for the heads up.
1599--
1600-- 20131118.9 Update for Lua 5.3... it seems that tostring(2/1) produces "2.0" instead of "2",
1601-- and this caused some problems.
1602--
1603-- 20131031.8 Unified the code for encode() and encode_pretty(); they had been stupidly separate,
1604-- and had of course diverged (encode_pretty didn't get the fixes that encode got, so
1605-- sometimes produced incorrect results; thanks to Mattie for the heads up).
1606--
1607-- Handle encoding tables with non-positive numeric keys (unlikely, but possible).
1608--
1609-- If a table has both numeric and string keys, or its numeric keys are inappropriate
1610-- (such as being non-positive or infinite), the numeric keys are turned into
1611-- string keys appropriate for a JSON object. So, as before,
1612-- JSON:encode({ "one", "two", "three" })
1613-- produces the array
1614-- ["one","two","three"]
1615-- but now something with mixed key types like
1616-- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" }))
1617-- instead of throwing an error produces an object:
1618-- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"}
1619--
1620-- To maintain the prior throw-an-error semantics, set
1621-- JSON.noKeyConversion = true
1622--
1623-- 20131004.7 Release under a Creative Commons CC-BY license, which I should have done from day one, sorry.
1624--
1625-- 20130120.6 Comment update: added a link to the specific page on my blog where this code can
1626-- be found, so that folks who come across the code outside of my blog can find updates
1627-- more easily.
1628--
1629-- 20111207.5 Added support for the 'etc' arguments, for better error reporting.
1630--
1631-- 20110731.4 More feedback from David Kolf on how to make the tests for Nan/Infinity system independent.
1632--
1633-- 20110730.3 Incorporated feedback from David Kolf at http://lua-users.org/wiki/JsonModules:
1634--
1635-- * When encoding lua for JSON, Sparse numeric arrays are now handled by
1636-- spitting out full arrays, such that
1637-- JSON:encode({"one", "two", [10] = "ten"})
1638-- returns
1639-- ["one","two",null,null,null,null,null,null,null,"ten"]
1640--
1641-- In 20100810.2 and earlier, only up to the first non-null value would have been retained.
1642--
1643-- * When encoding lua for JSON, numeric value NaN gets spit out as null, and infinity as "1+e9999".
1644-- Version 20100810.2 and earlier created invalid JSON in both cases.
1645--
1646-- * Unicode surrogate pairs are now detected when decoding JSON.
1647--
1648-- 20100810.2 added some checking to ensure that an invalid Unicode character couldn't leak in to the UTF-8 encoding
1649--
1650-- 20100731.1 initial public release
1651--