Advertisement
RadioNurshat

JSON.lua

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