HenryEx

libJSON

Aug 18th, 2026
4,635
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 69.33 KB | Source Code | 0 0
  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. --
  17. local VERSION = '20211016.28' -- version history at end of file
  18. local AUTHOR_NOTE = "-[ JSON.lua package by Jeffrey Friedl (http://regex.info/blog/lua/json) version 20211016.28 ]-"
  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. --
  25. local 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 DURING DECODE
  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 (and, an 'etc' argument had been
  81. --   provided to decode(), its value is tacked onto the message as well),
  82. --   and then calls JSON.assert(), which itself defaults to Lua's built-in
  83. --   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 'etc' argument allows stronger coordination between
  106. --   decoding and error reporting, especially when you provide your own
  107. --   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 JSON:onTrailingGarbage() simply invokes JSON:onDecodeError("trailing garbage"...),
  149. --   but you can have 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. -- DECODING AND STRICT PARSING
  177. --
  178. --   If strictParsing is true in your JSON object, or if you set strictParsing as a decode option,
  179. --   some kinds of technically-invalid JSON that would normally be accepted are rejected with an error.
  180. --
  181. --   For example, passing in an empty string
  182. --
  183. --      JSON:decode("")
  184. --
  185. --   normally succeeds with a return value of nil, but
  186. --
  187. --      JSON:decode("", nil, { strictParsing = true })
  188. --
  189. --   results in an error being raised (onDecodeError is called).
  190. --
  191. --      JSON.strictParsing = true
  192. --      JSON:decode("")
  193. --
  194. --   achieves the same thing.
  195. --
  196. --
  197. --
  198. -- ENCODING (from a lua table to a JSON string)
  199. --
  200. --   JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
  201. --
  202. --   local raw_json_text    = JSON:encode(lua_table_or_value)
  203. --   local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability
  204. --   local custom_pretty    = JSON:encode(lua_table_or_value, etc, { pretty = true, indent = "|  ", align_keys = false })
  205. --
  206. --   On error during encoding, this code calls:
  207. --
  208. --     JSON:onEncodeError(message, etc)
  209. --
  210. --   which you can override in your local JSON object. Also see "HANDLING UNSUPPORTED VALUE TYPES" below.
  211. --
  212. --   The 'etc' in the error call is the second argument to encode() and encode_pretty(), or nil if it wasn't provided.
  213. --
  214. --
  215. --
  216. --
  217. -- ENCODING OPTIONS
  218. --
  219. --   An optional third argument, a table of options, can be provided to encode().
  220. --
  221. --       encode_options =  {
  222. --           -- options for making "pretty" human-readable JSON (see "PRETTY-PRINTING" below)
  223. --           pretty         = true,   -- turn pretty formatting on
  224. --           indent         = "   ",  -- use this indent for each level of an array/object
  225. --           align_keys     = false,  -- if true, align the keys in a way that sounds like it should be nice, but is actually ugly
  226. --           array_newline  = false,  -- if true, array elements become one to a line rather than inline
  227. --          
  228. --           -- other output-related options
  229. --           null           = "\0",   -- see "ENCODING JSON NULL VALUES" below
  230. --           stringsAreUtf8 = false,  -- see "HANDLING UNICODE LINE AND PARAGRAPH SEPARATORS FOR JAVA" below
  231. --       }
  232. --  
  233. --       json_string = JSON:encode(mytable, etc, encode_options)
  234. --
  235. --
  236. --
  237. -- For reference, the defaults are:
  238. --
  239. --           pretty         = false
  240. --           null           = nil,
  241. --           stringsAreUtf8 = false,
  242. --
  243. --
  244. --
  245. -- PRETTY-PRINTING
  246. --
  247. --   Enabling the 'pretty' encode option helps generate human-readable JSON.
  248. --
  249. --     pretty = JSON:encode(val, etc, {
  250. --                                       pretty = true,
  251. --                                       indent = "   ",
  252. --                                       align_keys = false,
  253. --                                     })
  254. --
  255. --   encode_pretty() is also provided: it's identical to encode() except
  256. --   that encode_pretty() provides a default options table if none given in the call:
  257. --
  258. --       { pretty = true, indent = "  ", align_keys = false, array_newline = false }
  259. --
  260. --   For example, if
  261. --
  262. --      JSON:encode(data)
  263. --
  264. --   produces:
  265. --
  266. --      {"city":"Kyoto","climate":{"avg_temp":16,"humidity":"high","snowfall":"minimal"},"country":"Japan","wards":11}
  267. --
  268. --   then
  269. --
  270. --      JSON:encode_pretty(data)
  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. --   The following lines all return identical strings:
  286. --       JSON:encode_pretty(data)
  287. --       JSON:encode_pretty(data, nil, { pretty = true, indent = "  ", align_keys = false, array_newline = false})
  288. --       JSON:encode_pretty(data, nil, { pretty = true, indent = "  " })
  289. --       JSON:encode       (data, nil, { pretty = true, indent = "  " })
  290. --
  291. --   An example of setting your own indent string:
  292. --
  293. --     JSON:encode_pretty(data, nil, { pretty = true, indent = "|    " })
  294. --
  295. --   produces:
  296. --
  297. --      {
  298. --      |    "city": "Kyoto",
  299. --      |    "climate": {
  300. --      |    |    "avg_temp": 16,
  301. --      |    |    "humidity": "high",
  302. --      |    |    "snowfall": "minimal"
  303. --      |    },
  304. --      |    "country": "Japan",
  305. --      |    "wards": 11
  306. --      }
  307. --
  308. --   An example of setting align_keys to true:
  309. --
  310. --     JSON:encode_pretty(data, nil, { pretty = true, indent = "  ", align_keys = true })
  311. --  
  312. --   produces:
  313. --  
  314. --      {
  315. --           "city": "Kyoto",
  316. --        "climate": {
  317. --                     "avg_temp": 16,
  318. --                     "humidity": "high",
  319. --                     "snowfall": "minimal"
  320. --                   },
  321. --        "country": "Japan",
  322. --          "wards": 11
  323. --      }
  324. --
  325. --   which I must admit is kinda ugly, sorry. This was the default for
  326. --   encode_pretty() prior to version 20141223.14.
  327. --
  328. --
  329. --  HANDLING UNICODE LINE AND PARAGRAPH SEPARATORS FOR JAVA
  330. --
  331. --    If the 'stringsAreUtf8' encode option is set to true, consider Lua strings not as a sequence of bytes,
  332. --    but as a sequence of UTF-8 characters.
  333. --
  334. --    Currently, the only practical effect of setting this option is that Unicode LINE and PARAGRAPH
  335. --    separators, if found in a string, are encoded with a JSON escape instead of being dumped as is.
  336. --    The JSON is valid either way, but encoding this way, apparently, allows the resulting JSON
  337. --    to also be valid Java.
  338. --
  339. --  AMBIGUOUS SITUATIONS DURING THE ENCODING
  340. --
  341. --   During the encode, if a Lua table being encoded contains both string
  342. --   and numeric keys, it fits neither JSON's idea of an object, nor its
  343. --   idea of an array. To get around this, when any string key exists (or
  344. --   when non-positive numeric keys exist), numeric keys are converted to
  345. --   strings.
  346. --
  347. --   For example,
  348. --     JSON:encode({ "one", "two", "three", SOMESTRING = "some string" }))
  349. --   produces the JSON object
  350. --     {"1":"one","2":"two","3":"three","SOMESTRING":"some string"}
  351. --
  352. --   To prohibit this conversion and instead make it an error condition, set
  353. --      JSON.noKeyConversion = true
  354. --
  355. --
  356. -- ENCODING JSON NULL VALUES
  357. --
  358. --   Lua tables completely omit keys whose value is nil, so without special handling there's
  359. --   no way to represent JSON object's null value in a Lua table.  For example
  360. --      JSON:encode({ username = "admin", password = nil })
  361. --
  362. --   produces:
  363. --
  364. --      {"username":"admin"}
  365. --
  366. --   In order to actually produce
  367. --
  368. --      {"username":"admin", "password":null}
  369. --
  370.  
  371. --   one can include a string value for a "null" field in the options table passed to encode()....
  372. --   any Lua table entry with that value becomes null in the JSON output:
  373. --
  374. --      JSON:encode({ username = "admin", password = "xyzzy" }, -- First arg is the Lua table to encode as JSON.
  375. --                  nil,                                        -- Second arg is the 'etc' value, ignored here
  376. --                  { null = "xyzzy" })                         -- Third arg is th options table
  377. --
  378. --   produces:
  379. --
  380. --      {"username":"admin", "password":null}
  381. --
  382. --   Just be sure to use a string that is otherwise unlikely to appear in your data.
  383. --   The string "\0" (a string with one null byte) may well be appropriate for many applications.
  384. --
  385. --   The "null" options also applies to Lua tables that become JSON arrays.
  386. --      JSON:encode({ "one", "two", nil, nil })
  387. --
  388. --   produces
  389. --
  390. --      ["one","two"]
  391. --
  392. --   while
  393. --
  394. --      NullPlaceholder = "\0"
  395. --      encode_options = { null = NullPlaceholder }
  396. --      JSON:encode({ "one", "two", NullPlaceholder, NullPlaceholder}, nil, encode_options)
  397. --   produces
  398. --
  399. --      ["one","two",null,null]
  400. --
  401. --
  402. --
  403. -- HANDLING LARGE AND/OR PRECISE NUMBERS
  404. --
  405. --
  406. --   Without special handling, numbers in JSON can lose precision in Lua.
  407. --   For example:
  408. --  
  409. --      T = JSON:decode('{  "small":12345, "big":12345678901234567890123456789, "precise":9876.67890123456789012345  }')
  410. --
  411. --      print("small:   ",  type(T.small),    T.small)
  412. --      print("big:     ",  type(T.big),      T.big)
  413. --      print("precise: ",  type(T.precise),  T.precise)
  414. --  
  415. --   produces
  416. --  
  417. --      small:          number  12345
  418. --      big:            number  1.2345678901235e+28
  419. --      precise:        number  9876.6789012346
  420. --
  421. --   Precision is lost with both 'big' and 'precise'.
  422. --
  423. --   This package offers ways to try to handle this better (for some definitions of "better")...
  424. --
  425. --   The most precise method is by setting the global:
  426. --  
  427. --      JSON.decodeNumbersAsObjects = true
  428. --  
  429. --   When this is set, numeric JSON data is encoded into Lua in a form that preserves the exact
  430. --   JSON numeric presentation when re-encoded back out to JSON, or accessed in Lua as a string.
  431. --
  432. --   This is done by encoding the numeric data with a Lua table/metatable that returns
  433. --   the possibly-imprecise numeric form when accessed numerically, but the original precise
  434. --   representation when accessed as a string.
  435. --
  436. --   Consider the example above, with this option turned on:
  437. --
  438. --      JSON.decodeNumbersAsObjects = true
  439. --      
  440. --      T = JSON:decode('{  "small":12345, "big":12345678901234567890123456789, "precise":9876.67890123456789012345  }')
  441. --
  442. --      print("small:   ",  type(T.small),    T.small)
  443. --      print("big:     ",  type(T.big),      T.big)
  444. --      print("precise: ",  type(T.precise),  T.precise)
  445. --  
  446. --   This now produces:
  447. --  
  448. --      small:          table   12345
  449. --      big:            table   12345678901234567890123456789
  450. --      precise:        table   9876.67890123456789012345
  451. --  
  452. --   However, within Lua you can still use the values (e.g. T.precise in the example above) in numeric
  453. --   contexts. In such cases you'll get the possibly-imprecise numeric version, but in string contexts
  454. --   and when the data finds its way to this package's encode() function, the original full-precision
  455. --   representation is used.
  456. --
  457. --   You can force access to the string or numeric version via
  458. --        JSON:forceString()
  459. --        JSON:forceNumber()
  460. --   For example,
  461. --        local probably_okay = JSON:forceNumber(T.small) -- 'probably_okay' is a number
  462. --
  463. --   Code the inspects the JSON-turned-Lua data using type() can run into troubles because what used to
  464. --   be a number can now be a table (e.g. as the small/big/precise example above shows). Update these
  465. --   situations to use JSON:isNumber(item), which returns nil if the item is neither a number nor one
  466. --   of these number objects. If it is either, it returns the number itself. For completeness there's
  467. --   also JSON:isString(item).
  468. --
  469. --   If you want to try to avoid the hassles of this "number as an object" kludge for all but really
  470. --   big numbers, you can set JSON.decodeNumbersAsObjects and then also set one or both of
  471. --            JSON:decodeIntegerObjectificationLength
  472. --            JSON:decodeDecimalObjectificationLength
  473. --   They refer to the length of the part of the number before and after a decimal point. If they are
  474. --   set and their part is at least that number of digits, objectification occurs. If both are set,
  475. --   objectification occurs when either length is met.
  476. --
  477. --   -----------------------
  478. --
  479. --   Even without using the JSON.decodeNumbersAsObjects option, you can encode numbers in your Lua
  480. --   table that retain high precision upon encoding to JSON, by using the JSON:asNumber() function:
  481. --
  482. --      T = {
  483. --         imprecise =                123456789123456789.123456789123456789,
  484. --         precise   = JSON:asNumber("123456789123456789.123456789123456789")
  485. --      }
  486. --
  487. --      print(JSON:encode_pretty(T))
  488. --
  489. --   This produces:
  490. --
  491. --      {
  492. --         "precise": 123456789123456789.123456789123456789,
  493. --         "imprecise": 1.2345678912346e+17
  494. --      }
  495. --
  496. --
  497. --   -----------------------
  498. --
  499. --   A different way to handle big/precise JSON numbers is to have decode() merely return the exact
  500. --   string representation of the number instead of the number itself. This approach might be useful
  501. --   when the numbers are merely some kind of opaque object identifier and you want to work with them
  502. --   in Lua as strings anyway.
  503. --  
  504. --   This approach is enabled by setting
  505. --
  506. --      JSON.decodeIntegerStringificationLength = 10
  507. --
  508. --   The value is the number of digits (of the integer part of the number) at which to stringify numbers.
  509. --   NOTE: this setting is ignored if JSON.decodeNumbersAsObjects is true, as that takes precedence.
  510. --
  511. --   Consider our previous example with this option set to 10:
  512. --
  513. --      JSON.decodeIntegerStringificationLength = 10
  514. --      
  515. --      T = JSON:decode('{  "small":12345, "big":12345678901234567890123456789, "precise":9876.67890123456789012345  }')
  516. --
  517. --      print("small:   ",  type(T.small),    T.small)
  518. --      print("big:     ",  type(T.big),      T.big)
  519. --      print("precise: ",  type(T.precise),  T.precise)
  520. --
  521. --   This produces:
  522. --
  523. --      small:          number  12345
  524. --      big:            string  12345678901234567890123456789
  525. --      precise:        number  9876.6789012346
  526. --
  527. --   The long integer of the 'big' field is at least JSON.decodeIntegerStringificationLength digits
  528. --   in length, so it's converted not to a Lua integer but to a Lua string. Using a value of 0 or 1 ensures
  529. --   that all JSON numeric data becomes strings in Lua.
  530. --
  531. --   Note that unlike
  532. --      JSON.decodeNumbersAsObjects = true
  533. --   this stringification is simple and unintelligent: the JSON number simply becomes a Lua string, and that's the end of it.
  534. --   If the string is then converted back to JSON, it's still a string. After running the code above, adding
  535. --      print(JSON:encode(T))
  536. --   produces
  537. --      {"big":"12345678901234567890123456789","precise":9876.6789012346,"small":12345}
  538. --   which is unlikely to be desired.
  539. --
  540. --   There's a comparable option for the length of the decimal part of a number:
  541. --
  542. --      JSON.decodeDecimalStringificationLength
  543. --
  544. --   This can be used alone or in conjunction with
  545. --
  546. --      JSON.decodeIntegerStringificationLength
  547. --
  548. --   to trip stringification on precise numbers with at least JSON.decodeIntegerStringificationLength digits after
  549. --   the decimal point. (Both are ignored if JSON.decodeNumbersAsObjects is true.)
  550. --
  551. --   This example:
  552. --
  553. --      JSON.decodeIntegerStringificationLength = 10
  554. --      JSON.decodeDecimalStringificationLength =  5
  555. --
  556. --      T = JSON:decode('{  "small":12345, "big":12345678901234567890123456789, "precise":9876.67890123456789012345  }')
  557. --      
  558. --      print("small:   ",  type(T.small),    T.small)
  559. --      print("big:     ",  type(T.big),      T.big)
  560. --      print("precise: ",  type(T.precise),  T.precise)
  561. --
  562. --  produces:
  563. --
  564. --      small:          number  12345
  565. --      big:            string  12345678901234567890123456789
  566. --      precise:        string  9876.67890123456789012345
  567. --
  568. --
  569. --  HANDLING UNSUPPORTED VALUE TYPES
  570. --
  571. --   Among the encoding errors that might be raised is an attempt to convert a table value that has a type
  572. --   that this package hasn't accounted for: a function, userdata, or a thread. You can handle these types as table
  573. --   values (but not as table keys) if you supply a JSON:unsupportedTypeEncoder() method along the lines of the
  574. --   following example:
  575. --        
  576. --        function JSON:unsupportedTypeEncoder(value_of_unsupported_type)
  577. --           if type(value_of_unsupported_type) == 'function' then
  578. --              return "a function value"
  579. --           else
  580. --              return nil
  581. --           end
  582. --        end
  583. --        
  584. --   Your unsupportedTypeEncoder() method is actually called with a bunch of arguments:
  585. --
  586. --      self:unsupportedTypeEncoder(value, parents, etc, options, indent, for_key)
  587. --
  588. --   The 'value' is the function, thread, or userdata to be converted to JSON.
  589. --
  590. --   The 'etc' and 'options' arguments are those passed to the original encode(). The other arguments are
  591. --   probably of little interest; see the source code. (Note that 'for_key' is never true, as this function
  592. --   is invoked only on table values; table keys of these types still trigger the onEncodeError method.)
  593. --
  594. --   If your unsupportedTypeEncoder() method returns a string, it's inserted into the JSON as is.
  595. --   If it returns nil plus an error message, that error message is passed through to an onEncodeError invocation.
  596. --   If it returns only nil, processing falls through to a default onEncodeError invocation.
  597. --
  598. --   If you want to handle everything in a simple way:
  599. --
  600. --        function JSON:unsupportedTypeEncoder(value)
  601. --           return tostring(value)
  602. --        end
  603. --
  604. --
  605. -- SUMMARY OF METHODS YOU CAN OVERRIDE IN YOUR LOCAL LUA JSON OBJECT
  606. --
  607. --    assert
  608. --    onDecodeError
  609. --    onDecodeOfNilError
  610. --    onDecodeOfHTMLError
  611. --    onTrailingGarbage
  612. --    onEncodeError
  613. --    unsupportedTypeEncoder
  614. --
  615. --  If you want to create a separate Lua JSON object with its own error handlers,
  616. --  you can reload JSON.lua or use the :new() method.
  617. --
  618. ---------------------------------------------------------------------------
  619.  
  620. local default_pretty_indent  = "  "
  621. local default_pretty_options = { pretty = true, indent = default_pretty_indent, align_keys = false, array_newline = false }
  622.  
  623. local isArray  = { __tostring = function() return "JSON array"         end }  isArray.__index  = isArray
  624. local isObject = { __tostring = function() return "JSON object"        end }  isObject.__index = isObject
  625.  
  626. function OBJDEF:newArray(tbl)
  627.    return setmetatable(tbl or {}, isArray)
  628. end
  629.  
  630. function OBJDEF:newObject(tbl)
  631.    return setmetatable(tbl or {}, isObject)
  632. end
  633.  
  634.  
  635.  
  636.  
  637. local function getnum(op)
  638.    return type(op) == 'number' and op or op.N
  639. end
  640.  
  641. local isNumber = {
  642.    __tostring = function(T)  return T.S        end,
  643.    __unm      = function(op) return getnum(op) end,
  644.  
  645.    __concat   = function(op1, op2) return tostring(op1) .. tostring(op2) end,
  646.    __add      = function(op1, op2) return getnum(op1)   +   getnum(op2)  end,
  647.    __sub      = function(op1, op2) return getnum(op1)   -   getnum(op2)  end,
  648.    __mul      = function(op1, op2) return getnum(op1)   *   getnum(op2)  end,
  649.    __div      = function(op1, op2) return getnum(op1)   /   getnum(op2)  end,
  650.    __mod      = function(op1, op2) return getnum(op1)   %   getnum(op2)  end,
  651.    __pow      = function(op1, op2) return getnum(op1)   ^   getnum(op2)  end,
  652.    __lt       = function(op1, op2) return getnum(op1)   <   getnum(op2)  end,
  653.    __eq       = function(op1, op2) return getnum(op1)   ==  getnum(op2)  end,
  654.    __le       = function(op1, op2) return getnum(op1)   <=  getnum(op2)  end,
  655. }
  656. isNumber.__index = isNumber
  657.  
  658. function OBJDEF:asNumber(item)
  659.  
  660.    if getmetatable(item) == isNumber then
  661.       -- it's already a JSON number object.
  662.       return item
  663.    elseif type(item) == 'table' and type(item.S) == 'string' and type(item.N) == 'number' then
  664.       -- it's a number-object table that lost its metatable, so give it one
  665.       return setmetatable(item, isNumber)
  666.    else
  667.       -- the normal situation... given a number or a string representation of a number....
  668.       local holder = {
  669.          S = tostring(item), -- S is the representation of the number as a string, which remains precise
  670.          N = tonumber(item), -- N is the number as a Lua number.
  671.       }
  672.       return setmetatable(holder, isNumber)
  673.    end
  674. end
  675.  
  676. --
  677. -- Given an item that might be a normal string or number, or might be an 'isNumber' object defined above,
  678. -- return the string version. This shouldn't be needed often because the 'isNumber' object should autoconvert
  679. -- to a string in most cases, but it's here to allow it to be forced when needed.
  680. --
  681. function OBJDEF:forceString(item)
  682.    if type(item) == 'table' and type(item.S) == 'string' then
  683.       return item.S
  684.    else
  685.       return tostring(item)
  686.    end
  687. end
  688.  
  689. --
  690. -- Given an item that might be a normal string or number, or might be an 'isNumber' object defined above,
  691. -- return the numeric version.
  692. --
  693. function OBJDEF:forceNumber(item)
  694.    if type(item) == 'table' and type(item.N) == 'number' then
  695.       return item.N
  696.    else
  697.       return tonumber(item)
  698.    end
  699. end
  700.  
  701. --
  702. -- If the given item is a number, return it. Otherwise, return nil.
  703. -- This, this can be used both in a conditional and to access the number when you're not sure its form.
  704. --
  705. function OBJDEF:isNumber(item)
  706.    if type(item) == 'number' then
  707.       return item
  708.    elseif type(item) == 'table' and type(item.N) == 'number' then
  709.       return item.N
  710.    else
  711.       return nil
  712.    end
  713. end
  714.  
  715. function OBJDEF:isString(item)
  716.    if type(item) == 'string' then
  717.       return item
  718.    elseif type(item) == 'table' and type(item.S) == 'string' then
  719.       return item.S
  720.    else
  721.       return nil
  722.    end
  723. end
  724.  
  725.  
  726.  
  727.  
  728. --
  729. -- Some utf8 routines to deal with the fact that Lua handles only bytes
  730. --
  731. local function top_three_bits(val)
  732.    return math.floor(val / 0x20)
  733. end
  734.  
  735. local function top_four_bits(val)
  736.    return math.floor(val / 0x10)
  737. end
  738.  
  739. local function unicode_character_bytecount_based_on_first_byte(first_byte)
  740.    local W = string.byte(first_byte)
  741.    if W < 0x80 then
  742.       return 1
  743.    elseif (W == 0xC0) or (W == 0xC1) or (W >= 0x80 and W <= 0xBF) or (W >= 0xF5) then
  744.       -- this is an error -- W can't be the start of a utf8 character
  745.       return 0
  746.    elseif top_three_bits(W) == 0x06 then
  747.       return 2
  748.    elseif top_four_bits(W) == 0x0E then
  749.       return 3
  750.    else
  751.       return 4
  752.    end
  753. end
  754.  
  755.  
  756.  
  757. local function unicode_codepoint_as_utf8(codepoint)
  758.    --
  759.    -- codepoint is a number
  760.    --
  761.    if codepoint <= 127 then
  762.       return string.char(codepoint)
  763.  
  764.    elseif codepoint <= 2047 then
  765.       --
  766.       -- 110yyyxx 10xxxxxx         <-- useful notation from http://en.wikipedia.org/wiki/Utf8
  767.       --
  768.       local highpart = math.floor(codepoint / 0x40)
  769.       local lowpart  = codepoint - (0x40 * highpart)
  770.       return string.char(0xC0 + highpart,
  771.                          0x80 + lowpart)
  772.  
  773.    elseif codepoint <= 65535 then
  774.       --
  775.       -- 1110yyyy 10yyyyxx 10xxxxxx
  776.       --
  777.       local highpart  = math.floor(codepoint / 0x1000)
  778.       local remainder = codepoint - 0x1000 * highpart
  779.       local midpart   = math.floor(remainder / 0x40)
  780.       local lowpart   = remainder - 0x40 * midpart
  781.  
  782.       highpart = 0xE0 + highpart
  783.       midpart  = 0x80 + midpart
  784.       lowpart  = 0x80 + lowpart
  785.  
  786.       --
  787.       -- Check for an invalid character (thanks Andy R. at Adobe).
  788.       -- See table 3.7, page 93, in http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf#G28070
  789.       --
  790.       if ( highpart == 0xE0 and midpart < 0xA0 ) or
  791.          ( highpart == 0xED and midpart > 0x9F ) or
  792.          ( highpart == 0xF0 and midpart < 0x90 ) or
  793.          ( highpart == 0xF4 and midpart > 0x8F )
  794.       then
  795.          return "?"
  796.       else
  797.          return string.char(highpart,
  798.                             midpart,
  799.                             lowpart)
  800.       end
  801.  
  802.    else
  803.       --
  804.       -- 11110zzz 10zzyyyy 10yyyyxx 10xxxxxx
  805.       --
  806.       local highpart  = math.floor(codepoint / 0x40000)
  807.       local remainder = codepoint - 0x40000 * highpart
  808.       local midA      = math.floor(remainder / 0x1000)
  809.       remainder       = remainder - 0x1000 * midA
  810.       local midB      = math.floor(remainder / 0x40)
  811.       local lowpart   = remainder - 0x40 * midB
  812.  
  813.       return string.char(0xF0 + highpart,
  814.                          0x80 + midA,
  815.                          0x80 + midB,
  816.                          0x80 + lowpart)
  817.    end
  818. end
  819.  
  820. function OBJDEF:onDecodeError(message, text, location, etc)
  821.    if text then
  822.       if location then
  823.          message = string.format("%s at byte %d of: %s", message, location, text)
  824.       else
  825.          message = string.format("%s: %s", message, text)
  826.       end
  827.    end
  828.  
  829.    if etc ~= nil then
  830.       message = message .. " (" .. OBJDEF:encode(etc) .. ")"
  831.    end
  832.  
  833.    if self.assert then
  834.       self.assert(false, message)
  835.    else
  836.       assert(false, message)
  837.    end
  838. end
  839.  
  840. function OBJDEF:onTrailingGarbage(json_text, location, parsed_value, etc)
  841.    return self:onDecodeError("trailing garbage", json_text, location, etc)
  842. end
  843.  
  844. OBJDEF.onDecodeOfNilError  = OBJDEF.onDecodeError
  845. OBJDEF.onDecodeOfHTMLError = OBJDEF.onDecodeError
  846.  
  847. function OBJDEF:onEncodeError(message, etc)
  848.    if etc ~= nil then
  849.       message = message .. " (" .. OBJDEF:encode(etc) .. ")"
  850.    end
  851.  
  852.    if self.assert then
  853.       self.assert(false, message)
  854.    else
  855.       assert(false, message)
  856.    end
  857. end
  858.  
  859. local function grok_number(self, text, start, options)
  860.    --
  861.    -- Grab the integer part
  862.    --
  863.    local integer_part = text:match('^-?[1-9]%d*', start)
  864.                      or text:match("^-?0",        start)
  865.  
  866.    if not integer_part then
  867.       self:onDecodeError("expected number", text, start, options.etc)
  868.       return nil, start -- in case the error method doesn't abort, return something sensible
  869.    end
  870.  
  871.    local i = start + integer_part:len()
  872.  
  873.    --
  874.    -- Grab an optional decimal part
  875.    --
  876.    local decimal_part = text:match('^%.%d+', i) or ""
  877.  
  878.    i = i + decimal_part:len()
  879.  
  880.    --
  881.    -- Grab an optional exponential part
  882.    --
  883.    local exponent_part = text:match('^[eE][-+]?%d+', i) or ""
  884.  
  885.    i = i + exponent_part:len()
  886.  
  887.    local full_number_text = integer_part .. decimal_part .. exponent_part
  888.  
  889.    if options.decodeNumbersAsObjects then
  890.  
  891.       local objectify = false
  892.  
  893.       if not options.decodeIntegerObjectificationLength and not options.decodeDecimalObjectificationLength then
  894.          -- no options, so objectify
  895.          objectify = true
  896.  
  897.       elseif (options.decodeIntegerObjectificationLength
  898.           and
  899.          (integer_part:len() >= options.decodeIntegerObjectificationLength or exponent_part:len() > 0))
  900.  
  901.           or
  902.          (options.decodeDecimalObjectificationLength
  903.           and
  904.           (decimal_part:len() >= options.decodeDecimalObjectificationLength  or exponent_part:len() > 0))
  905.       then
  906.          -- have options and they are triggered, so objectify
  907.          objectify = true
  908.       end
  909.  
  910.       if objectify then
  911.          return OBJDEF:asNumber(full_number_text), i
  912.       end
  913.       -- else, fall through to try to return as a straight-up number
  914.  
  915.    else
  916.  
  917.       -- Not always decoding numbers as objects, so perhaps encode as strings?
  918.  
  919.       --
  920.       -- If we're told to stringify only under certain conditions, so do.
  921.       -- We punt a bit when there's an exponent by just stringifying no matter what.
  922.       -- I suppose we should really look to see whether the exponent is actually big enough one
  923.       -- way or the other to trip stringification, but I'll be lazy about it until someone asks.
  924.       --
  925.       if (options.decodeIntegerStringificationLength
  926.           and
  927.          (integer_part:len() >= options.decodeIntegerStringificationLength or exponent_part:len() > 0))
  928.  
  929.           or
  930.  
  931.          (options.decodeDecimalStringificationLength
  932.           and
  933.           (decimal_part:len() >= options.decodeDecimalStringificationLength or exponent_part:len() > 0))
  934.       then
  935.          return full_number_text, i -- this returns the exact string representation seen in the original JSON
  936.       end
  937.  
  938.    end
  939.  
  940.  
  941.    local as_number = tonumber(full_number_text)
  942.  
  943.    if not as_number then
  944.       self:onDecodeError("bad number", text, start, options.etc)
  945.       return nil, start -- in case the error method doesn't abort, return something sensible
  946.    end
  947.  
  948.    return as_number, i
  949. end
  950.  
  951.  
  952. local backslash_escape_conversion = {
  953.    ['"'] = '"',
  954.    ['/'] = "/",
  955.    ['\\'] = "\\",
  956.    ['b'] = "\b",
  957.    ['f'] = "\f",
  958.    ['n'] = "\n",
  959.    ['r'] = "\r",
  960.    ['t'] = "\t",
  961. }
  962.  
  963. local function grok_string(self, text, start, options)
  964.  
  965.    if text:sub(start,start) ~= '"' then
  966.       self:onDecodeError("expected string's opening quote", text, start, options.etc)
  967.       return nil, start -- in case the error method doesn't abort, return something sensible
  968.    end
  969.  
  970.    local i = start + 1 -- +1 to bypass the initial quote
  971.    local text_len = text:len()
  972.    local VALUE = ""
  973.    while i <= text_len do
  974.       local c = text:sub(i,i)
  975.       if c == '"' then
  976.          return VALUE, i + 1
  977.       end
  978.       if c ~= '\\' then
  979.          
  980.          -- should grab the next bytes as per the number of bytes for this utf8 character
  981.          local byte_count = unicode_character_bytecount_based_on_first_byte(c)
  982.  
  983.          local next_character
  984.          if byte_count == 0 then
  985.             self:onDecodeError("non-utf8 sequence", text, i, options.etc)
  986.          elseif byte_count == 1 then
  987.             if options.strictParsing and string.byte(c) < 0x20 then
  988.                self:onDecodeError("Unescaped control character", text, i+1, options.etc)
  989.                return nil, start -- in case the error method doesn't abort, return something sensible
  990.             end
  991.             next_character = c
  992.          elseif byte_count == 2 then
  993.             next_character = text:match('^(.[\128-\191])', i)
  994.          elseif byte_count == 3 then
  995.             next_character = text:match('^(.[\128-\191][\128-\191])', i)
  996.          elseif byte_count == 4 then
  997.             next_character = text:match('^(.[\128-\191][\128-\191][\128-\191])', i)
  998.          end
  999.  
  1000.          if not next_character then
  1001.             self:onDecodeError("incomplete utf8 sequence", text, i, options.etc)
  1002.             return nil, i -- in case the error method doesn't abort, return something sensible          
  1003.          end
  1004.  
  1005.  
  1006.          VALUE = VALUE .. next_character
  1007.          i = i + byte_count
  1008.  
  1009.       else
  1010.          --
  1011.          -- We have a backslash escape
  1012.          --
  1013.          i = i + 1
  1014.  
  1015.          local next_byte = text:match('^(.)', i)
  1016.  
  1017.          if next_byte == nil then
  1018.             -- string ended after the \
  1019.             self:onDecodeError("unfinished \\ escape", text, i, options.etc)
  1020.             return nil, start -- in case the error method doesn't abort, return something sensible
  1021.          end
  1022.  
  1023.          if backslash_escape_conversion[next_byte] then
  1024.             VALUE = VALUE .. backslash_escape_conversion[next_byte]
  1025.             i = i + 1
  1026.          else
  1027.             --
  1028.             -- The only other valid use of \ that remains is in the form of \u####
  1029.             --
  1030.  
  1031.             local hex = text:match('^u([0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i)
  1032.             if hex then
  1033.                i = i + 5 -- bypass what we just read
  1034.  
  1035.                -- We have a Unicode codepoint. It could be standalone, or if in the proper range and
  1036.                -- followed by another in a specific range, it'll be a two-code surrogate pair.
  1037.                local codepoint = tonumber(hex, 16)
  1038.                if codepoint >= 0xD800 and codepoint <= 0xDBFF then
  1039.                   -- it's a hi surrogate... see whether we have a following low
  1040.                   local lo_surrogate = text:match('^\\u([dD][cdefCDEF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i)
  1041.                   if lo_surrogate then
  1042.                      i = i + 6 -- bypass the low surrogate we just read
  1043.                      codepoint = 0x2400 + (codepoint - 0xD800) * 0x400 + tonumber(lo_surrogate, 16)
  1044.                   else
  1045.                      -- not a proper low, so we'll just leave the first codepoint as is and spit it out.
  1046.                   end
  1047.                end
  1048.                VALUE = VALUE .. unicode_codepoint_as_utf8(codepoint)
  1049.  
  1050.             elseif options.strictParsing then
  1051.                --local next_byte = text:match('^\\(.)', i) printf("NEXT[%s]", next_byte);
  1052.                self:onDecodeError("illegal use of backslash escape", text, i, options.etc)
  1053.                return nil, start -- in case the error method doesn't abort, return something sensible
  1054.             else
  1055.                local byte_count = unicode_character_bytecount_based_on_first_byte(next_byte)
  1056.                if byte_count == 0 then
  1057.                   self:onDecodeError("non-utf8 sequence after backslash escape", text, i, options.etc)
  1058.                   return nil, start -- in case the error method doesn't abort, return something sensible
  1059.                end
  1060.  
  1061.                local next_character
  1062.                if byte_count == 1 then
  1063.                   next_character = next_byte
  1064.                elseif byte_count == 2 then
  1065.                   next_character = text:match('^(.[\128-\191])', i)
  1066.                elseif byte_count == 3 then
  1067.                   next_character = text:match('^(.[\128-\191][\128-\191])', i)
  1068.                elseif byte_count == 3 then
  1069.                   next_character = text:match('^(.[\128-\191][\128-\191][\128-\191])', i)
  1070.                end
  1071.  
  1072.                if next_character == nil then
  1073.                   -- incomplete utf8 character after escape
  1074.                   self:onDecodeError("incomplete utf8 sequence after backslash escape", text, i, options.etc)
  1075.                   return nil, start -- in case the error method doesn't abort, return something sensible
  1076.                end
  1077.  
  1078.                VALUE = VALUE .. next_character
  1079.                i = i + byte_count
  1080.             end
  1081.          end
  1082.       end
  1083.    end
  1084.  
  1085.    self:onDecodeError("unclosed string", text, start, options.etc)
  1086.    return nil, start -- in case the error method doesn't abort, return something sensible
  1087. end
  1088.  
  1089. local function skip_whitespace(text, start)
  1090.  
  1091.    local _, match_end = text:find("^[ \n\r\t]+", start) -- [ https://datatracker.ietf.org/doc/html/rfc7158#section-2 ]
  1092.    if match_end then
  1093.       return match_end + 1
  1094.    else
  1095.       return start
  1096.    end
  1097. end
  1098.  
  1099. local grok_one -- assigned later
  1100.  
  1101. local function grok_object(self, text, start, options)
  1102.  
  1103.    if text:sub(start,start) ~= '{' then
  1104.       self:onDecodeError("expected '{'", text, start, options.etc)
  1105.       return nil, start -- in case the error method doesn't abort, return something sensible
  1106.    end
  1107.  
  1108.    local i = skip_whitespace(text, start + 1) -- +1 to skip the '{'
  1109.  
  1110.    local VALUE = self.strictTypes and self:newObject { } or { }
  1111.  
  1112.    if text:sub(i,i) == '}' then
  1113.       return VALUE, i + 1
  1114.    end
  1115.    local text_len = text:len()
  1116.    while i <= text_len do
  1117.       local key, new_i = grok_string(self, text, i, options)
  1118.  
  1119.       i = skip_whitespace(text, new_i)
  1120.  
  1121.       if text:sub(i, i) ~= ':' then
  1122.          self:onDecodeError("expected colon", text, i, options.etc)
  1123.          return nil, i -- in case the error method doesn't abort, return something sensible
  1124.       end
  1125.  
  1126.       i = skip_whitespace(text, i + 1)
  1127.  
  1128.       local new_val, new_i = grok_one(self, text, i, options)
  1129.  
  1130.       VALUE[key] = new_val
  1131.  
  1132.       --
  1133.       -- Expect now either '}' to end things, or a ',' to allow us to continue.
  1134.       --
  1135.       i = skip_whitespace(text, new_i)
  1136.  
  1137.       local c = text:sub(i,i)
  1138.  
  1139.       if c == '}' then
  1140.          return VALUE, i + 1
  1141.       end
  1142.  
  1143.       if text:sub(i, i) ~= ',' then
  1144.          self:onDecodeError("expected comma or '}'", text, i, options.etc)
  1145.          return nil, i -- in case the error method doesn't abort, return something sensible
  1146.       end
  1147.  
  1148.       i = skip_whitespace(text, i + 1)
  1149.    end
  1150.  
  1151.    self:onDecodeError("unclosed '{'", text, start, options.etc)
  1152.    return nil, start -- in case the error method doesn't abort, return something sensible
  1153. end
  1154.  
  1155. local function grok_array(self, text, start, options)
  1156.    if text:sub(start,start) ~= '[' then
  1157.       self:onDecodeError("expected '['", text, start, options.etc)
  1158.       return nil, start -- in case the error method doesn't abort, return something sensible
  1159.    end
  1160.  
  1161.    local i = skip_whitespace(text, start + 1) -- +1 to skip the '['
  1162.    local VALUE = self.strictTypes and self:newArray { } or { }
  1163.    if text:sub(i,i) == ']' then
  1164.       return VALUE, i + 1
  1165.    end
  1166.  
  1167.    local VALUE_INDEX = 1
  1168.  
  1169.    local text_len = text:len()
  1170.    while i <= text_len do
  1171.       local val, new_i = grok_one(self, text, i, options)
  1172.  
  1173.       -- can't table.insert(VALUE, val) here because it's a no-op if val is nil
  1174.       VALUE[VALUE_INDEX] = val
  1175.       VALUE_INDEX = VALUE_INDEX + 1
  1176.  
  1177.       i = skip_whitespace(text, new_i)
  1178.  
  1179.       --
  1180.       -- Expect now either ']' to end things, or a ',' to allow us to continue.
  1181.       --
  1182.       local c = text:sub(i,i)
  1183.       if c == ']' then
  1184.          return VALUE, i + 1
  1185.       end
  1186.       if text:sub(i, i) ~= ',' then
  1187.          self:onDecodeError("expected comma or ']'", text, i, options.etc)
  1188.          return nil, i -- in case the error method doesn't abort, return something sensible
  1189.       end
  1190.       i = skip_whitespace(text, i + 1)
  1191.    end
  1192.    self:onDecodeError("unclosed '['", text, start, options.etc)
  1193.    return nil, i -- in case the error method doesn't abort, return something sensible
  1194. end
  1195.  
  1196.  
  1197. grok_one = function(self, text, start, options)
  1198.    -- Skip any whitespace
  1199.    start = skip_whitespace(text, start)
  1200.  
  1201.    if start > text:len() then
  1202.       self:onDecodeError("unexpected end of string", text, nil, options.etc)
  1203.       return nil, start -- in case the error method doesn't abort, return something sensible
  1204.    end
  1205.  
  1206.    if text:find('^"', start) then
  1207.       return grok_string(self, text, start, options)
  1208.  
  1209.    elseif text:find('^[-0123456789 ]', start) then
  1210.       return grok_number(self, text, start, options)
  1211.  
  1212.    elseif text:find('^%{', start) then
  1213.       return grok_object(self, text, start, options)
  1214.  
  1215.    elseif text:find('^%[', start) then
  1216.       return grok_array(self, text, start, options)
  1217.  
  1218.    elseif text:find('^true', start) then
  1219.       return true, start + 4
  1220.  
  1221.    elseif text:find('^false', start) then
  1222.       return false, start + 5
  1223.  
  1224.    elseif text:find('^null', start) then
  1225.       return options.null, start + 4
  1226.  
  1227.    else
  1228.       self:onDecodeError("can't parse JSON", text, start, options.etc)
  1229.       return nil, 1 -- in case the error method doesn't abort, return something sensible
  1230.    end
  1231. end
  1232.  
  1233. function OBJDEF:decode(text, etc, options)
  1234.    --
  1235.    -- If the user didn't pass in a table of decode options, make an empty one.
  1236.    --
  1237.    if type(options) ~= 'table' then
  1238.       options = {}
  1239.    end
  1240.  
  1241.    --
  1242.    -- If they passed in an 'etc' argument, stuff it into the options.
  1243.    -- (If not, any 'etc' field in the options they passed in remains to be used)
  1244.    --
  1245.    if etc ~= nil then
  1246.       options.etc = etc
  1247.    end
  1248.  
  1249.  
  1250.    --
  1251.    -- apply global options
  1252.    --
  1253.    if options.decodeNumbersAsObjects == nil then
  1254.       options.decodeNumbersAsObjects = self.decodeNumbersAsObjects
  1255.    end
  1256.    if options.decodeIntegerObjectificationLength == nil then
  1257.       options.decodeIntegerObjectificationLength = self.decodeIntegerObjectificationLength
  1258.    end
  1259.    if options.decodeDecimalObjectificationLength == nil then
  1260.       options.decodeDecimalObjectificationLength = self.decodeDecimalObjectificationLength
  1261.    end
  1262.    if options.decodeIntegerStringificationLength == nil then
  1263.       options.decodeIntegerStringificationLength = self.decodeIntegerStringificationLength
  1264.    end
  1265.    if options.decodeDecimalStringificationLength == nil then
  1266.       options.decodeDecimalStringificationLength = self.decodeDecimalStringificationLength
  1267.    end
  1268.    if options.strictParsing == nil then
  1269.       options.strictParsing = self.strictParsing
  1270.    end
  1271.  
  1272.  
  1273.    if type(self) ~= 'table' or self.__index ~= OBJDEF then
  1274.       local error_message = "JSON:decode must be called in method format"
  1275.       OBJDEF:onDecodeError(error_message, nil, nil, options.etc)
  1276.       return nil, error_message -- in case the error method doesn't abort, return something sensible
  1277.    end
  1278.  
  1279.    if text == nil then
  1280.       local error_message = "nil passed to JSON:decode()"
  1281.       self:onDecodeOfNilError(error_message, nil, nil, options.etc)
  1282.       return nil, error_message -- in case the error method doesn't abort, return something sensible
  1283.  
  1284.    elseif type(text) ~= 'string' then
  1285.       local error_message = "expected string argument to JSON:decode()"
  1286.       self:onDecodeError(string.format("%s, got %s", error_message, type(text)), nil, nil, options.etc)
  1287.       return nil, error_message -- in case the error method doesn't abort, return something sensible
  1288.    end
  1289.  
  1290.    -- If passed an empty string....
  1291.    if text:match('^%s*$') then
  1292.       if options.strictParsing then
  1293.          local error_message = "empty string passed to JSON:decode()"
  1294.          self:onDecodeOfNilError(error_message, nil, nil, options.etc)
  1295.          return nil, error_message -- in case the error method doesn't abort, return something sensible
  1296.       else
  1297.          -- we'll consider it nothing, but not an error
  1298.          return nil
  1299.       end
  1300.    end
  1301.  
  1302.    if text:match('^%s*<') then
  1303.       -- Can't be JSON... we'll assume it's HTML
  1304.       local error_message = "HTML passed to JSON:decode()"
  1305.       self:onDecodeOfHTMLError(error_message, text, nil, options.etc)
  1306.       return nil, error_message -- in case the error method doesn't abort, return something sensible
  1307.    end
  1308.  
  1309.    --
  1310.    -- Ensure that it's not UTF-32 or UTF-16.
  1311.    -- Those are perfectly valid encodings for JSON (as per RFC 4627 section 3),
  1312.    -- but this package can't handle them.
  1313.    --
  1314.    if text:sub(1,1):byte() == 0 or (text:len() >= 2 and text:sub(2,2):byte() == 0) then
  1315.       local error_message = "JSON package groks only UTF-8, sorry"
  1316.       self:onDecodeError(error_message, text, nil, options.etc)
  1317.       return nil, error_message -- in case the error method doesn't abort, return something sensible
  1318.    end
  1319.  
  1320.  
  1321.    --
  1322.    -- Finally, go parse it
  1323.    --
  1324.    local success, value, next_i = pcall(grok_one, self, text, 1, options)
  1325.  
  1326.    if success then
  1327.  
  1328.       local error_message = nil
  1329.       if next_i ~= #text + 1 then
  1330.          -- something's left over after we parsed the first thing.... whitespace is allowed.
  1331.          next_i = skip_whitespace(text, next_i)
  1332.  
  1333.          -- if we have something left over now, it's trailing garbage
  1334.          if next_i ~= #text + 1 then
  1335.             value, error_message = self:onTrailingGarbage(text, next_i, value, options.etc)
  1336.          end
  1337.       end
  1338.       return value, error_message
  1339.  
  1340.    else
  1341.  
  1342.       -- If JSON:onDecodeError() didn't abort out of the pcall, we'll have received
  1343.       -- the error message here as "value", so pass it along as an assert.
  1344.       local error_message = value
  1345.       if self.assert then
  1346.          self.assert(false, error_message)
  1347.       else
  1348.          assert(false, error_message)
  1349.       end
  1350.       -- ...and if we're still here (because the assert didn't throw an error),
  1351.       -- return a nil and throw the error message on as a second arg
  1352.       return nil, error_message
  1353.  
  1354.    end
  1355. end
  1356.  
  1357. local function backslash_replacement_function(c)
  1358.    if     c == "\n" then     return "\\n"
  1359.    elseif c == "\r" then     return "\\r"
  1360.    elseif c == "\t" then     return "\\t"
  1361.    elseif c == "\b" then     return "\\b"
  1362.    elseif c == "\f" then     return "\\f"
  1363.    elseif c == '"' then      return '\\"'
  1364.    elseif c == '\\' then     return '\\\\'
  1365.    elseif c == '/' then      return '/'
  1366.    else
  1367.       return string.format("\\u%04x", c:byte())
  1368.    end
  1369. end
  1370.  
  1371. local chars_to_be_escaped_in_JSON_string
  1372.    = '['
  1373.    ..    '"'    -- class sub-pattern to match a double quote
  1374.    ..    '%\\'  -- class sub-pattern to match a backslash
  1375.    ..    '/'    -- class sub-pattern to match a forwardslash
  1376.    ..    '%z'   -- class sub-pattern to match a null
  1377.    ..    '\001' .. '-' .. '\031' -- class sub-pattern to match control characters
  1378.    .. ']'
  1379.  
  1380.  
  1381. local LINE_SEPARATOR_as_utf8      = unicode_codepoint_as_utf8(0x2028)
  1382. local PARAGRAPH_SEPARATOR_as_utf8 = unicode_codepoint_as_utf8(0x2029)
  1383. local function json_string_literal(value, options)
  1384.    local newval = value:gsub(chars_to_be_escaped_in_JSON_string, backslash_replacement_function)
  1385.    if options.stringsAreUtf8 then
  1386.       --
  1387.       -- This feels really ugly to just look into a string for the sequence of bytes that we know to be a particular utf8 character,
  1388.       -- but utf8 was designed purposefully to make this kind of thing possible. Still, feels dirty.
  1389.       -- I'd rather decode the byte stream into a character stream, but it's not technically needed so
  1390.       -- not technically worth it.
  1391.       --
  1392.       newval = newval:gsub(LINE_SEPARATOR_as_utf8, '\\u2028'):gsub(PARAGRAPH_SEPARATOR_as_utf8,'\\u2029')
  1393.    end
  1394.    return '"' .. newval .. '"'
  1395. end
  1396.  
  1397. local function object_or_array(self, T, etc)
  1398.    --
  1399.    -- We need to inspect all the keys... if there are any strings, we'll convert to a JSON
  1400.    -- object. If there are only numbers, it's a JSON array.
  1401.    --
  1402.    -- If we'll be converting to a JSON object, we'll want to sort the keys so that the
  1403.    -- end result is deterministic.
  1404.    --
  1405.    local string_keys = { }
  1406.    local number_keys = { }
  1407.    local number_keys_must_be_strings = false
  1408.    local maximum_number_key
  1409.  
  1410.    for key in pairs(T) do
  1411.       if type(key) == 'string' then
  1412.          table.insert(string_keys, key)
  1413.       elseif type(key) == 'number' then
  1414.          table.insert(number_keys, key)
  1415.          if key <= 0 or key >= math.huge then
  1416.             number_keys_must_be_strings = true
  1417.          elseif not maximum_number_key or key > maximum_number_key then
  1418.             maximum_number_key = key
  1419.          end
  1420.       elseif type(key) == 'boolean' then
  1421.          table.insert(string_keys, tostring(key))
  1422.       else
  1423.          self:onEncodeError("can't encode table with a key of type " .. type(key), etc)
  1424.       end
  1425.    end
  1426.  
  1427.    if #string_keys == 0 and not number_keys_must_be_strings then
  1428.       --
  1429.       -- An empty table, or a numeric-only array
  1430.       --
  1431.       if #number_keys > 0 then
  1432.          return nil, maximum_number_key -- an array
  1433.       elseif tostring(T) == "JSON array" then
  1434.          return nil
  1435.       elseif tostring(T) == "JSON object" then
  1436.          return { }
  1437.       else
  1438.          -- have to guess, so we'll pick array, since empty arrays are likely more common than empty objects
  1439.          return nil
  1440.       end
  1441.    end
  1442.  
  1443.    table.sort(string_keys)
  1444.  
  1445.    local map
  1446.    if #number_keys > 0 then
  1447.       --
  1448.       -- If we're here then we have either mixed string/number keys, or numbers inappropriate for a JSON array
  1449.       -- It's not ideal, but we'll turn the numbers into strings so that we can at least create a JSON object.
  1450.       --
  1451.  
  1452.       if self.noKeyConversion then
  1453.          self:onEncodeError("a table with both numeric and string keys could be an object or array; aborting", etc)
  1454.       end
  1455.  
  1456.       --
  1457.       -- Have to make a shallow copy of the source table so we can remap the numeric keys to be strings
  1458.       --
  1459.       map = { }
  1460.       for key, val in pairs(T) do
  1461.          map[key] = val
  1462.       end
  1463.  
  1464.       table.sort(number_keys)
  1465.  
  1466.       --
  1467.       -- Throw numeric keys in there as strings
  1468.       --
  1469.       for _, number_key in ipairs(number_keys) do
  1470.          local string_key = tostring(number_key)
  1471.          if map[string_key] == nil then
  1472.             table.insert(string_keys , string_key)
  1473.             map[string_key] = T[number_key]
  1474.          else
  1475.             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)
  1476.          end
  1477.       end
  1478.    end
  1479.  
  1480.    return string_keys, nil, map
  1481. end
  1482.  
  1483. --
  1484. -- Encode
  1485. --
  1486. -- 'options' is nil, or a table with possible keys:
  1487. --
  1488. --    pretty         -- If true, return a pretty-printed version.
  1489. --
  1490. --    indent         -- A string (usually of spaces) used to indent each nested level.
  1491. --
  1492. --    align_keys     -- If true, align all the keys when formatting a table. The result is uglier than one might at first imagine.
  1493. --                      Results are undefined if 'align_keys' is true but 'pretty' is not.
  1494. --
  1495. --    array_newline  -- If true, array elements are formatted each to their own line. The default is to all fall inline.
  1496. --                      Results are undefined if 'array_newline' is true but 'pretty' is not.
  1497. --
  1498. --    null           -- If this exists with a string value, table elements with this value are output as JSON null.
  1499. --
  1500. --    stringsAreUtf8 -- If true, consider Lua strings not as a sequence of bytes, but as a sequence of UTF-8 characters.
  1501. --                      (Currently, the only practical effect of setting this option is that Unicode LINE and PARAGRAPH
  1502. --                       separators, if found in a string, are encoded with a JSON escape instead of as raw UTF-8.
  1503. --                       The JSON is valid either way, but encoding this way, apparently, allows the resulting JSON
  1504. --                       to also be valid Java.)
  1505. --
  1506. --
  1507. local function encode_value(self, value, parents, etc, options, indent, for_key)
  1508.  
  1509.    --
  1510.    -- keys in a JSON object can never be null, so we don't even consider options.null when converting a key value
  1511.    --
  1512.    if value == nil or (not for_key and options and options.null and value == options.null) then
  1513.       return 'null'
  1514.  
  1515.    elseif type(value) == 'string' then
  1516.       return json_string_literal(value, options)
  1517.  
  1518.    elseif type(value) == 'number' then
  1519.       if value ~= value then
  1520.          --
  1521.          -- NaN (Not a Number).
  1522.          -- JSON has no NaN, so we have to fudge the best we can. This should really be a package option.
  1523.          --
  1524.          return "null"
  1525.       elseif value >= math.huge then
  1526.          --
  1527.          -- Positive infinity. JSON has no INF, so we have to fudge the best we can. This should
  1528.          -- really be a package option. Note: at least with some implementations, positive infinity
  1529.          -- is both ">= math.huge" and "<= -math.huge", which makes no sense but that's how it is.
  1530.          -- Negative infinity is properly "<= -math.huge". So, we must be sure to check the ">="
  1531.          -- case first.
  1532.          --
  1533.          return "1e+9999"
  1534.       elseif value <= -math.huge then
  1535.          --
  1536.          -- Negative infinity.
  1537.          -- JSON has no INF, so we have to fudge the best we can. This should really be a package option.
  1538.          --
  1539.          return "-1e+9999"
  1540.       else
  1541.          return tostring(value)
  1542.       end
  1543.  
  1544.    elseif type(value) == 'boolean' then
  1545.       return tostring(value)
  1546.  
  1547.    elseif type(value) ~= 'table' then
  1548.  
  1549.       if self.unsupportedTypeEncoder then
  1550.          local user_value, user_error = self:unsupportedTypeEncoder(value, parents, etc, options, indent, for_key)
  1551.          -- If the user's handler returns a string, use that. If it returns nil plus an error message, bail with that.
  1552.          -- If only nil returned, fall through to the default error handler.
  1553.          if type(user_value) == 'string' then
  1554.             return user_value
  1555.          elseif user_value ~= nil then
  1556.             self:onEncodeError("unsupportedTypeEncoder method returned a " .. type(user_value), etc)
  1557.          elseif user_error then
  1558.             self:onEncodeError(tostring(user_error), etc)
  1559.          end
  1560.       end
  1561.  
  1562.       self:onEncodeError("can't convert " .. type(value) .. " to JSON", etc)
  1563.  
  1564.    elseif getmetatable(value) == isNumber then
  1565.       return tostring(value)
  1566.    else
  1567.       --
  1568.       -- A table to be converted to either a JSON object or array.
  1569.       --
  1570.       local T = value
  1571.  
  1572.       if type(options) ~= 'table' then
  1573.          options = {}
  1574.       end
  1575.       if type(indent) ~= 'string' then
  1576.          indent = ""
  1577.       end
  1578.  
  1579.       if parents[T] then
  1580.          self:onEncodeError("table " .. tostring(T) .. " is a child of itself", etc)
  1581.       else
  1582.          parents[T] = true
  1583.       end
  1584.  
  1585.       local result_value
  1586.  
  1587.       local object_keys, maximum_number_key, map = object_or_array(self, T, etc)
  1588.       if maximum_number_key then
  1589.          --
  1590.          -- An array...
  1591.          --
  1592.          local key_indent
  1593.          if options.array_newline then
  1594.             key_indent = indent .. tostring(options.indent or "")
  1595.          else
  1596.             key_indent = indent
  1597.          end
  1598.  
  1599.          local ITEMS = { }
  1600.          for i = 1, maximum_number_key do
  1601.             table.insert(ITEMS, encode_value(self, T[i], parents, etc, options, key_indent))
  1602.          end
  1603.  
  1604.          if options.array_newline then
  1605.             result_value = "[\n" .. key_indent .. table.concat(ITEMS, ",\n" .. key_indent) .. "\n" .. indent .. "]"
  1606.          elseif options.pretty then
  1607.             result_value = "[ " .. table.concat(ITEMS, ", ") .. " ]"
  1608.          else
  1609.             result_value = "["  .. table.concat(ITEMS, ",")  .. "]"
  1610.          end
  1611.  
  1612.       elseif object_keys then
  1613.          --
  1614.          -- An object
  1615.          --
  1616.          local TT = map or T
  1617.  
  1618.          if options.pretty then
  1619.  
  1620.             local KEYS = { }
  1621.             local max_key_length = 0
  1622.             for _, key in ipairs(object_keys) do
  1623.                local encoded = encode_value(self, tostring(key), parents, etc, options, indent, true)
  1624.                if options.align_keys then
  1625.                   max_key_length = math.max(max_key_length, #encoded)
  1626.                end
  1627.                table.insert(KEYS, encoded)
  1628.             end
  1629.             local key_indent = indent .. tostring(options.indent or "")
  1630.             local subtable_indent = key_indent .. string.rep(" ", max_key_length) .. (options.align_keys and "  " or "")
  1631.             local FORMAT = "%s%" .. string.format("%d", max_key_length) .. "s: %s"
  1632.  
  1633.             local COMBINED_PARTS = { }
  1634.             for i, key in ipairs(object_keys) do
  1635.                local encoded_val = encode_value(self, TT[key], parents, etc, options, subtable_indent)
  1636.                table.insert(COMBINED_PARTS, string.format(FORMAT, key_indent, KEYS[i], encoded_val))
  1637.             end
  1638.             result_value = "{\n" .. table.concat(COMBINED_PARTS, ",\n") .. "\n" .. indent .. "}"
  1639.  
  1640.          else
  1641.  
  1642.             local PARTS = { }
  1643.             for _, key in ipairs(object_keys) do
  1644.                local encoded_val = encode_value(self, TT[key],       parents, etc, options, indent)
  1645.                local encoded_key = encode_value(self, tostring(key), parents, etc, options, indent, true)
  1646.                table.insert(PARTS, string.format("%s:%s", encoded_key, encoded_val))
  1647.             end
  1648.             result_value = "{" .. table.concat(PARTS, ",") .. "}"
  1649.  
  1650.          end
  1651.       else
  1652.          --
  1653.          -- An empty array/object... we'll treat it as an array, though it should really be an option
  1654.          --
  1655.          result_value = "[]"
  1656.       end
  1657.  
  1658.       parents[T] = false
  1659.       return result_value
  1660.    end
  1661. end
  1662.  
  1663. local function top_level_encode(self, value, etc, options)
  1664.    local val = encode_value(self, value, {}, etc, options)
  1665.    if val == nil then
  1666.       --PRIVATE("may need to revert to the previous public verison if I can't figure out what the guy wanted")
  1667.       return val
  1668.    else
  1669.       return val
  1670.    end
  1671. end
  1672.  
  1673. function OBJDEF:encode(value, etc, options)
  1674.    if type(self) ~= 'table' or self.__index ~= OBJDEF then
  1675.       OBJDEF:onEncodeError("JSON:encode must be called in method format", etc)
  1676.    end
  1677.  
  1678.    --
  1679.    -- If the user didn't pass in a table of decode options, make an empty one.
  1680.    --
  1681.    if type(options) ~= 'table' then
  1682.       options = {}
  1683.    end
  1684.  
  1685.    return top_level_encode(self, value, etc, options)
  1686. end
  1687.  
  1688. function OBJDEF:encode_pretty(value, etc, options)
  1689.    if type(self) ~= 'table' or self.__index ~= OBJDEF then
  1690.       OBJDEF:onEncodeError("JSON:encode_pretty must be called in method format", etc)
  1691.    end
  1692.  
  1693.    --
  1694.    -- If the user didn't pass in a table of decode options, use the default pretty ones
  1695.    --
  1696.    if type(options) ~= 'table' then
  1697.       options = default_pretty_options
  1698.    end
  1699.  
  1700.    return top_level_encode(self, value, etc, options)
  1701. end
  1702.  
  1703. --function OBJDEF.__tostring()
  1704. --   return "JSON encode/decode package"
  1705. --end
  1706.  
  1707. --OBJDEF.__index = OBJDEF
  1708.  
  1709. function OBJDEF:new(args)
  1710.    local new = { }
  1711.  
  1712.    if args then
  1713.       for key, val in pairs(args) do
  1714.          new[key] = val
  1715.       end
  1716.    end
  1717.  
  1718.    return setmetatable(new, OBJDEF)
  1719. end
  1720.  
  1721. --return OBJDEF:new()
  1722. JSON = OBJDEF
  1723.  
  1724. --
  1725. -- Version history:
  1726. --
  1727. --   20211016.28   Had forgotten to document the strictParsing option.
  1728. --
  1729. --   20211015.27   Better handle some edge-case errors [ thank you http://seriot.ch/projects/parsing_json.html ; all tests are now successful ]
  1730. --
  1731. --                 Added some semblance of proper UTF8 parsing, and now aborts with an error on ilformatted UTF8.
  1732. --
  1733. --                 Added the strictParsing option:
  1734. --                    Aborts with an error on unknown backslash-escape in strings
  1735. --                    Aborts on naked control characters in strings
  1736. --                    Aborts when decode is passed a whitespace-only string
  1737. --
  1738. --                 For completeness, when encoding a Lua string into a JSON string, escape a forward slash.
  1739. --
  1740. --                 String decoding should be a bit more efficient now.
  1741. --
  1742. --   20170927.26   Use option.null in decoding as well. Thanks to Max Sindwani for the bump, and sorry to Oliver Hitz
  1743. --                 whose first mention of it four years ago was completely missed by me.
  1744. --
  1745. --   20170823.25   Added support for JSON:unsupportedTypeEncoder().
  1746. --                 Thanks to Chronos Phaenon Eosphoros (https://github.com/cpeosphoros) for the idea.
  1747. --
  1748. --   20170819.24   Added support for boolean keys in tables.
  1749. --
  1750. --   20170416.23   Added the "array_newline" formatting option suggested by yurenchen (http://www.yurenchen.com/)
  1751. --
  1752. --   20161128.22   Added:
  1753. --                   JSON:isString()
  1754. --                   JSON:isNumber()
  1755. --                   JSON:decodeIntegerObjectificationLength
  1756. --                   JSON:decodeDecimalObjectificationLength
  1757. --
  1758. --   20161109.21   Oops, had a small boo-boo in the previous update.
  1759. --
  1760. --   20161103.20   Used to silently ignore trailing garbage when decoding. Now fails via JSON:onTrailingGarbage()
  1761. --                 http://seriot.ch/parsing_json.php
  1762. --
  1763. --                 Built-in error message about "expected comma or ']'" had mistakenly referred to '['
  1764. --
  1765. --                 Updated the built-in error reporting to refer to bytes rather than characters.
  1766. --
  1767. --                 The decode() method no longer assumes that error handlers abort.
  1768. --
  1769. --                 Made the VERSION string a string instead of a number
  1770. --
  1771.  
  1772. --   20160916.19   Fixed the isNumber.__index assignment (thanks to Jack Taylor)
  1773. --  
  1774. --   20160730.18   Added JSON:forceString() and JSON:forceNumber()
  1775. --
  1776. --   20160728.17   Added concatenation to the metatable for JSON:asNumber()
  1777. --
  1778. --   20160709.16   Could crash if not passed an options table (thanks jarno heikkinen <[email protected]>).
  1779. --
  1780. --                 Made JSON:asNumber() a bit more resilient to being passed the results of itself.
  1781. --
  1782. --   20160526.15   Added the ability to easily encode null values in JSON, via the new "null" encoding option.
  1783. --                 (Thanks to Adam B for bringing up the issue.)
  1784. --
  1785. --                 Added some support for very large numbers and precise floats via
  1786. --                    JSON.decodeNumbersAsObjects
  1787. --                    JSON.decodeIntegerStringificationLength
  1788. --                    JSON.decodeDecimalStringificationLength
  1789. --
  1790. --                 Added the "stringsAreUtf8" encoding option. (Hat tip to http://lua-users.org/wiki/JsonModules )
  1791. --
  1792. --   20141223.14   The encode_pretty() routine produced fine results for small datasets, but isn't really
  1793. --                 appropriate for anything large, so with help from Alex Aulbach I've made the encode routines
  1794. --                 more flexible, and changed the default encode_pretty() to be more generally useful.
  1795. --
  1796. --                 Added a third 'options' argument to the encode() and encode_pretty() routines, to control
  1797. --                 how the encoding takes place.
  1798. --
  1799. --                 Updated docs to add assert() call to the loadfile() line, just as good practice so that
  1800. --                 if there is a problem loading JSON.lua, the appropriate error message will percolate up.
  1801. --
  1802. --   20140920.13   Put back (in a way that doesn't cause warnings about unused variables) the author string,
  1803. --                 so that the source of the package, and its version number, are visible in compiled copies.
  1804. --
  1805. --   20140911.12   Minor lua cleanup.
  1806. --                 Fixed internal reference to 'JSON.noKeyConversion' to reference 'self' instead of 'JSON'.
  1807. --                 (Thanks to SmugMug's David Parry for these.)
  1808. --
  1809. --   20140418.11   JSON nulls embedded within an array were being ignored, such that
  1810. --                     ["1",null,null,null,null,null,"seven"],
  1811. --                 would return
  1812. --                     {1,"seven"}
  1813. --                 It's now fixed to properly return
  1814. --                     {1, nil, nil, nil, nil, nil, "seven"}
  1815. --                 Thanks to "haddock" for catching the error.
  1816. --
  1817. --   20140116.10   The user's JSON.assert() wasn't always being used. Thanks to "blue" for the heads up.
  1818. --
  1819. --   20131118.9    Update for Lua 5.3... it seems that tostring(2/1) produces "2.0" instead of "2",
  1820. --                 and this caused some problems.
  1821. --
  1822. --   20131031.8    Unified the code for encode() and encode_pretty(); they had been stupidly separate,
  1823. --                 and had of course diverged (encode_pretty didn't get the fixes that encode got, so
  1824. --                 sometimes produced incorrect results; thanks to Mattie for the heads up).
  1825. --
  1826. --                 Handle encoding tables with non-positive numeric keys (unlikely, but possible).
  1827. --
  1828. --                 If a table has both numeric and string keys, or its numeric keys are inappropriate
  1829. --                 (such as being non-positive or infinite), the numeric keys are turned into
  1830. --                 string keys appropriate for a JSON object. So, as before,
  1831. --                         JSON:encode({ "one", "two", "three" })
  1832. --                 produces the array
  1833. --                         ["one","two","three"]
  1834. --                 but now something with mixed key types like
  1835. --                         JSON:encode({ "one", "two", "three", SOMESTRING = "some string" }))
  1836. --                 instead of throwing an error produces an object:
  1837. --                         {"1":"one","2":"two","3":"three","SOMESTRING":"some string"}
  1838. --
  1839. --                 To maintain the prior throw-an-error semantics, set
  1840. --                      JSON.noKeyConversion = true
  1841. --                
  1842. --   20131004.7    Release under a Creative Commons CC-BY license, which I should have done from day one, sorry.
  1843. --
  1844. --   20130120.6    Comment update: added a link to the specific page on my blog where this code can
  1845. --                 be found, so that folks who come across the code outside of my blog can find updates
  1846. --                 more easily.
  1847. --
  1848. --   20111207.5    Added support for the 'etc' arguments, for better error reporting.
  1849. --
  1850. --   20110731.4    More feedback from David Kolf on how to make the tests for Nan/Infinity system independent.
  1851. --
  1852. --   20110730.3    Incorporated feedback from David Kolf at http://lua-users.org/wiki/JsonModules:
  1853. --
  1854. --                   * When encoding lua for JSON, Sparse numeric arrays are now handled by
  1855. --                     spitting out full arrays, such that
  1856. --                        JSON:encode({"one", "two", [10] = "ten"})
  1857. --                     returns
  1858. --                        ["one","two",null,null,null,null,null,null,null,"ten"]
  1859. --
  1860. --                     In 20100810.2 and earlier, only up to the first non-null value would have been retained.
  1861. --
  1862. --                   * When encoding lua for JSON, numeric value NaN gets spit out as null, and infinity as "1+e9999".
  1863. --                     Version 20100810.2 and earlier created invalid JSON in both cases.
  1864. --
  1865. --                   * Unicode surrogate pairs are now detected when decoding JSON.
  1866. --
  1867. --   20100810.2    added some checking to ensure that an invalid Unicode character couldn't leak in to the UTF-8 encoding
  1868. --
  1869. --   20100731.1    initial public release
  1870. --
  1871.  
Advertisement