Advertisement
Guest User

Untitled

a guest
Nov 12th, 2016
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 55.29 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 = '20161103.20' -- version history at end of file
  18. local AUTHOR_NOTE = "-[ JSON.lua package by Jeffrey Friedl (http://regex.info/blog/lua/json) version 20161103.20 ]-"
  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. if next_i ~= #text + 1 then
  1061. -- something's left over after we parsed the first thing.... whitespace is allowed.
  1062. next_i = skip_whitespace(text, next_i)
  1063.  
  1064. -- if we have something left over now, it's trailing garbage
  1065. local error_message
  1066. if next_i ~= #text + 1 then
  1067. value, error_message = self:onTrailingGarbage(text, next_i, value, options.etc)
  1068. end
  1069. end
  1070. return value, error_message
  1071.  
  1072. else
  1073.  
  1074. -- If JSON:onDecodeError() didn't abort out of the pcall, we'll have received
  1075. -- the error message here as "value", so pass it along as an assert.
  1076. local error_message = value
  1077. if self.assert then
  1078. self.assert(false, error_message)
  1079. else
  1080. assert(false, error_message)
  1081. end
  1082. -- and if we're still here, return a nil and throw the error message on as a second arg
  1083. return nil, error_message
  1084.  
  1085. end
  1086. end
  1087.  
  1088. local function backslash_replacement_function(c)
  1089. if c == "\n" then
  1090. return "\\n"
  1091. elseif c == "\r" then
  1092. return "\\r"
  1093. elseif c == "\t" then
  1094. return "\\t"
  1095. elseif c == "\b" then
  1096. return "\\b"
  1097. elseif c == "\f" then
  1098. return "\\f"
  1099. elseif c == '"' then
  1100. return '\\"'
  1101. elseif c == '\\' then
  1102. return '\\\\'
  1103. else
  1104. return string.format("\\u%04x", c:byte())
  1105. end
  1106. end
  1107.  
  1108. local chars_to_be_escaped_in_JSON_string
  1109. = '['
  1110. .. '"' -- class sub-pattern to match a double quote
  1111. .. '%\\' -- class sub-pattern to match a backslash
  1112. .. '%z' -- class sub-pattern to match a null
  1113. .. '\001' .. '-' .. '\031' -- class sub-pattern to match control characters
  1114. .. ']'
  1115.  
  1116.  
  1117. local LINE_SEPARATOR_as_utf8 = unicode_codepoint_as_utf8(0x2028)
  1118. local PARAGRAPH_SEPARATOR_as_utf8 = unicode_codepoint_as_utf8(0x2029)
  1119. local function json_string_literal(value, options)
  1120. local newval = value:gsub(chars_to_be_escaped_in_JSON_string, backslash_replacement_function)
  1121. if options.stringsAreUtf8 then
  1122. --
  1123. -- This feels really ugly to just look into a string for the sequence of bytes that we know to be a particular utf8 character,
  1124. -- but utf8 was designed purposefully to make this kind of thing possible. Still, feels dirty.
  1125. -- I'd rather decode the byte stream into a character stream, but it's not technically needed so
  1126. -- not technically worth it.
  1127. --
  1128. newval = newval:gsub(LINE_SEPARATOR_as_utf8, '\\u2028'):gsub(PARAGRAPH_SEPARATOR_as_utf8,'\\u2029')
  1129. end
  1130. return '"' .. newval .. '"'
  1131. end
  1132.  
  1133. local function object_or_array(self, T, etc)
  1134. --
  1135. -- We need to inspect all the keys... if there are any strings, we'll convert to a JSON
  1136. -- object. If there are only numbers, it's a JSON array.
  1137. --
  1138. -- If we'll be converting to a JSON object, we'll want to sort the keys so that the
  1139. -- end result is deterministic.
  1140. --
  1141. local string_keys = { }
  1142. local number_keys = { }
  1143. local number_keys_must_be_strings = false
  1144. local maximum_number_key
  1145.  
  1146. for key in pairs(T) do
  1147. if type(key) == 'string' then
  1148. table.insert(string_keys, key)
  1149. elseif type(key) == 'number' then
  1150. table.insert(number_keys, key)
  1151. if key <= 0 or key >= math.huge then
  1152. number_keys_must_be_strings = true
  1153. elseif not maximum_number_key or key > maximum_number_key then
  1154. maximum_number_key = key
  1155. end
  1156. else
  1157. self:onEncodeError("can't encode table with a key of type " .. type(key), etc)
  1158. end
  1159. end
  1160.  
  1161. if #string_keys == 0 and not number_keys_must_be_strings then
  1162. --
  1163. -- An empty table, or a numeric-only array
  1164. --
  1165. if #number_keys > 0 then
  1166. return nil, maximum_number_key -- an array
  1167. elseif tostring(T) == "JSON array" then
  1168. return nil
  1169. elseif tostring(T) == "JSON object" then
  1170. return { }
  1171. else
  1172. -- have to guess, so we'll pick array, since empty arrays are likely more common than empty objects
  1173. return nil
  1174. end
  1175. end
  1176.  
  1177. table.sort(string_keys)
  1178.  
  1179. local map
  1180. if #number_keys > 0 then
  1181. --
  1182. -- If we're here then we have either mixed string/number keys, or numbers inappropriate for a JSON array
  1183. -- It's not ideal, but we'll turn the numbers into strings so that we can at least create a JSON object.
  1184. --
  1185.  
  1186. if self.noKeyConversion then
  1187. self:onEncodeError("a table with both numeric and string keys could be an object or array; aborting", etc)
  1188. end
  1189.  
  1190. --
  1191. -- Have to make a shallow copy of the source table so we can remap the numeric keys to be strings
  1192. --
  1193. map = { }
  1194. for key, val in pairs(T) do
  1195. map[key] = val
  1196. end
  1197.  
  1198. table.sort(number_keys)
  1199.  
  1200. --
  1201. -- Throw numeric keys in there as strings
  1202. --
  1203. for _, number_key in ipairs(number_keys) do
  1204. local string_key = tostring(number_key)
  1205. if map[string_key] == nil then
  1206. table.insert(string_keys , string_key)
  1207. map[string_key] = T[number_key]
  1208. else
  1209. 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)
  1210. end
  1211. end
  1212. end
  1213.  
  1214. return string_keys, nil, map
  1215. end
  1216.  
  1217. --
  1218. -- Encode
  1219. --
  1220. -- 'options' is nil, or a table with possible keys:
  1221. --
  1222. -- pretty -- If true, return a pretty-printed version.
  1223. --
  1224. -- indent -- A string (usually of spaces) used to indent each nested level.
  1225. --
  1226. -- align_keys -- If true, align all the keys when formatting a table.
  1227. --
  1228. -- null -- If this exists with a string value, table elements with this value are output as JSON null.
  1229. --
  1230. -- stringsAreUtf8 -- If true, consider Lua strings not as a sequence of bytes, but as a sequence of UTF-8 characters.
  1231. -- (Currently, the only practical effect of setting this option is that Unicode LINE and PARAGRAPH
  1232. -- separators, if found in a string, are encoded with a JSON escape instead of as raw UTF-8.
  1233. -- The JSON is valid either way, but encoding this way, apparently, allows the resulting JSON
  1234. -- to also be valid Java.)
  1235. --
  1236. --
  1237. local encode_value -- must predeclare because it calls itself
  1238. function encode_value(self, value, parents, etc, options, indent, for_key)
  1239.  
  1240. --
  1241. -- keys in a JSON object can never be null, so we don't even consider options.null when converting a key value
  1242. --
  1243. if value == nil or (not for_key and options and options.null and value == options.null) then
  1244. return 'null'
  1245.  
  1246. elseif type(value) == 'string' then
  1247. return json_string_literal(value, options)
  1248.  
  1249. elseif type(value) == 'number' then
  1250. if value ~= value then
  1251. --
  1252. -- NaN (Not a Number).
  1253. -- JSON has no NaN, so we have to fudge the best we can. This should really be a package option.
  1254. --
  1255. return "null"
  1256. elseif value >= math.huge then
  1257. --
  1258. -- Positive infinity. JSON has no INF, so we have to fudge the best we can. This should
  1259. -- really be a package option. Note: at least with some implementations, positive infinity
  1260. -- is both ">= math.huge" and "<= -math.huge", which makes no sense but that's how it is.
  1261. -- Negative infinity is properly "<= -math.huge". So, we must be sure to check the ">="
  1262. -- case first.
  1263. --
  1264. return "1e+9999"
  1265. elseif value <= -math.huge then
  1266. --
  1267. -- Negative infinity.
  1268. -- JSON has no INF, so we have to fudge the best we can. This should really be a package option.
  1269. --
  1270. return "-1e+9999"
  1271. else
  1272. return tostring(value)
  1273. end
  1274.  
  1275. elseif type(value) == 'boolean' then
  1276. return tostring(value)
  1277.  
  1278. elseif type(value) ~= 'table' then
  1279. self:onEncodeError("can't convert " .. type(value) .. " to JSON", etc)
  1280.  
  1281. elseif getmetatable(value) == isNumber then
  1282. return tostring(value)
  1283. else
  1284. --
  1285. -- A table to be converted to either a JSON object or array.
  1286. --
  1287. local T = value
  1288.  
  1289. if type(options) ~= 'table' then
  1290. options = {}
  1291. end
  1292. if type(indent) ~= 'string' then
  1293. indent = ""
  1294. end
  1295.  
  1296. if parents[T] then
  1297. self:onEncodeError("table " .. tostring(T) .. " is a child of itself", etc)
  1298. else
  1299. parents[T] = true
  1300. end
  1301.  
  1302. local result_value
  1303.  
  1304. local object_keys, maximum_number_key, map = object_or_array(self, T, etc)
  1305. if maximum_number_key then
  1306. --
  1307. -- An array...
  1308. --
  1309. local ITEMS = { }
  1310. for i = 1, maximum_number_key do
  1311. table.insert(ITEMS, encode_value(self, T[i], parents, etc, options, indent))
  1312. end
  1313.  
  1314. if options.pretty then
  1315. result_value = "[ " .. table.concat(ITEMS, ", ") .. " ]"
  1316. else
  1317. result_value = "[" .. table.concat(ITEMS, ",") .. "]"
  1318. end
  1319.  
  1320. elseif object_keys then
  1321. --
  1322. -- An object
  1323. --
  1324. local TT = map or T
  1325.  
  1326. if options.pretty then
  1327.  
  1328. local KEYS = { }
  1329. local max_key_length = 0
  1330. for _, key in ipairs(object_keys) do
  1331. local encoded = encode_value(self, tostring(key), parents, etc, options, indent, true)
  1332. if options.align_keys then
  1333. max_key_length = math.max(max_key_length, #encoded)
  1334. end
  1335. table.insert(KEYS, encoded)
  1336. end
  1337. local key_indent = indent .. tostring(options.indent or "")
  1338. local subtable_indent = key_indent .. string.rep(" ", max_key_length) .. (options.align_keys and " " or "")
  1339. local FORMAT = "%s%" .. string.format("%d", max_key_length) .. "s: %s"
  1340.  
  1341. local COMBINED_PARTS = { }
  1342. for i, key in ipairs(object_keys) do
  1343. local encoded_val = encode_value(self, TT[key], parents, etc, options, subtable_indent)
  1344. table.insert(COMBINED_PARTS, string.format(FORMAT, key_indent, KEYS[i], encoded_val))
  1345. end
  1346. result_value = "{\n" .. table.concat(COMBINED_PARTS, ",\n") .. "\n" .. indent .. "}"
  1347.  
  1348. else
  1349.  
  1350. local PARTS = { }
  1351. for _, key in ipairs(object_keys) do
  1352. local encoded_val = encode_value(self, TT[key], parents, etc, options, indent)
  1353. local encoded_key = encode_value(self, tostring(key), parents, etc, options, indent, true)
  1354. table.insert(PARTS, string.format("%s:%s", encoded_key, encoded_val))
  1355. end
  1356. result_value = "{" .. table.concat(PARTS, ",") .. "}"
  1357.  
  1358. end
  1359. else
  1360. --
  1361. -- An empty array/object... we'll treat it as an array, though it should really be an option
  1362. --
  1363. result_value = "[]"
  1364. end
  1365.  
  1366. parents[T] = false
  1367. return result_value
  1368. end
  1369. end
  1370.  
  1371. local function top_level_encode(self, value, etc, options)
  1372. local val = encode_value(self, value, {}, etc, options)
  1373. if val == nil then
  1374. --PRIVATE("may need to revert to the previous public verison if I can't figure out what the guy wanted")
  1375. return val
  1376. else
  1377. return val
  1378. end
  1379. end
  1380.  
  1381. function OBJDEF:encode(value, etc, options)
  1382. if type(self) ~= 'table' or self.__index ~= OBJDEF then
  1383. OBJDEF:onEncodeError("JSON:encode must be called in method format", etc)
  1384. end
  1385.  
  1386. --
  1387. -- If the user didn't pass in a table of decode options, make an empty one.
  1388. --
  1389. if type(options) ~= 'table' then
  1390. options = {}
  1391. end
  1392.  
  1393. return top_level_encode(self, value, etc, options)
  1394. end
  1395.  
  1396. function OBJDEF:encode_pretty(value, etc, options)
  1397. if type(self) ~= 'table' or self.__index ~= OBJDEF then
  1398. OBJDEF:onEncodeError("JSON:encode_pretty must be called in method format", etc)
  1399. end
  1400.  
  1401. --
  1402. -- If the user didn't pass in a table of decode options, use the default pretty ones
  1403. --
  1404. if type(options) ~= 'table' then
  1405. options = default_pretty_options
  1406. end
  1407.  
  1408. return top_level_encode(self, value, etc, options)
  1409. end
  1410.  
  1411. function OBJDEF.__tostring()
  1412. return "JSON encode/decode package"
  1413. end
  1414.  
  1415. OBJDEF.__index = OBJDEF
  1416.  
  1417. function OBJDEF:new(args)
  1418. local new = { }
  1419.  
  1420. if args then
  1421. for key, val in pairs(args) do
  1422. new[key] = val
  1423. end
  1424. end
  1425.  
  1426. return setmetatable(new, OBJDEF)
  1427. end
  1428.  
  1429. return OBJDEF:new()
  1430.  
  1431. --
  1432. -- Version history:
  1433. --
  1434. -- 20161103.20 Used to silently ignore trailing garbage when decoding. Now fails via JSON:onTrailingGarbage()
  1435. -- http://seriot.ch/parsing_json.php
  1436. --
  1437. -- Built-in error message about "expected comma or ']'" had mistakenly referred to '['
  1438. --
  1439. -- Updated the built-in error reporting to refer to bytes rather than characters.
  1440. --
  1441. -- The decode() method no longer assumes that error handlers abort.
  1442. --
  1443. -- Made the VERSION string a string instead of a number
  1444. --
  1445. --
  1446. -- 20160916.19 Fixed the isNumber.__index assignment (thanks to Jack Taylor)
  1447. --
  1448. -- 20160730.18 Added JSON:forceString() and JSON:forceNumber()
  1449. --
  1450. -- 20160728.17 Added concatenation to the metatable for JSON:asNumber()
  1451. --
  1452. -- 20160709.16 Could crash if not passed an options table (thanks jarno heikkinen <jarnoh@capturemonkey.com>).
  1453. --
  1454. -- Made JSON:asNumber() a bit more resilient to being passed the results of itself.
  1455. --
  1456. -- 20160526.15 Added the ability to easily encode null values in JSON, via the new "null" encoding option.
  1457. -- (Thanks to Adam B for bringing up the issue.)
  1458. --
  1459. -- Added some support for very large numbers and precise floats via
  1460. -- JSON.decodeNumbersAsObjects
  1461. -- JSON.decodeIntegerStringificationLength
  1462. -- JSON.decodeDecimalStringificationLength
  1463. --
  1464. -- Added the "stringsAreUtf8" encoding option. (Hat tip to http://lua-users.org/wiki/JsonModules )
  1465. --
  1466. -- 20141223.14 The encode_pretty() routine produced fine results for small datasets, but isn't really
  1467. -- appropriate for anything large, so with help from Alex Aulbach I've made the encode routines
  1468. -- more flexible, and changed the default encode_pretty() to be more generally useful.
  1469. --
  1470. -- Added a third 'options' argument to the encode() and encode_pretty() routines, to control
  1471. -- how the encoding takes place.
  1472. --
  1473. -- Updated docs to add assert() call to the loadfile() line, just as good practice so that
  1474. -- if there is a problem loading JSON.lua, the appropriate error message will percolate up.
  1475. --
  1476. -- 20140920.13 Put back (in a way that doesn't cause warnings about unused variables) the author string,
  1477. -- so that the source of the package, and its version number, are visible in compiled copies.
  1478. --
  1479. -- 20140911.12 Minor lua cleanup.
  1480. -- Fixed internal reference to 'JSON.noKeyConversion' to reference 'self' instead of 'JSON'.
  1481. -- (Thanks to SmugMug's David Parry for these.)
  1482. --
  1483. -- 20140418.11 JSON nulls embedded within an array were being ignored, such that
  1484. -- ["1",null,null,null,null,null,"seven"],
  1485. -- would return
  1486. -- {1,"seven"}
  1487. -- It's now fixed to properly return
  1488. -- {1, nil, nil, nil, nil, nil, "seven"}
  1489. -- Thanks to "haddock" for catching the error.
  1490. --
  1491. -- 20140116.10 The user's JSON.assert() wasn't always being used. Thanks to "blue" for the heads up.
  1492. --
  1493. -- 20131118.9 Update for Lua 5.3... it seems that tostring(2/1) produces "2.0" instead of "2",
  1494. -- and this caused some problems.
  1495. --
  1496. -- 20131031.8 Unified the code for encode() and encode_pretty(); they had been stupidly separate,
  1497. -- and had of course diverged (encode_pretty didn't get the fixes that encode got, so
  1498. -- sometimes produced incorrect results; thanks to Mattie for the heads up).
  1499. --
  1500. -- Handle encoding tables with non-positive numeric keys (unlikely, but possible).
  1501. --
  1502. -- If a table has both numeric and string keys, or its numeric keys are inappropriate
  1503. -- (such as being non-positive or infinite), the numeric keys are turned into
  1504. -- string keys appropriate for a JSON object. So, as before,
  1505. -- JSON:encode({ "one", "two", "three" })
  1506. -- produces the array
  1507. -- ["one","two","three"]
  1508. -- but now something with mixed key types like
  1509. -- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" }))
  1510. -- instead of throwing an error produces an object:
  1511. -- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"}
  1512. --
  1513. -- To maintain the prior throw-an-error semantics, set
  1514. -- JSON.noKeyConversion = true
  1515. --
  1516. -- 20131004.7 Release under a Creative Commons CC-BY license, which I should have done from day one, sorry.
  1517. --
  1518. -- 20130120.6 Comment update: added a link to the specific page on my blog where this code can
  1519. -- be found, so that folks who come across the code outside of my blog can find updates
  1520. -- more easily.
  1521. --
  1522. -- 20111207.5 Added support for the 'etc' arguments, for better error reporting.
  1523. --
  1524. -- 20110731.4 More feedback from David Kolf on how to make the tests for Nan/Infinity system independent.
  1525. --
  1526. -- 20110730.3 Incorporated feedback from David Kolf at http://lua-users.org/wiki/JsonModules:
  1527. --
  1528. -- * When encoding lua for JSON, Sparse numeric arrays are now handled by
  1529. -- spitting out full arrays, such that
  1530. -- JSON:encode({"one", "two", [10] = "ten"})
  1531. -- returns
  1532. -- ["one","two",null,null,null,null,null,null,null,"ten"]
  1533. --
  1534. -- In 20100810.2 and earlier, only up to the first non-null value would have been retained.
  1535. --
  1536. -- * When encoding lua for JSON, numeric value NaN gets spit out as null, and infinity as "1+e9999".
  1537. -- Version 20100810.2 and earlier created invalid JSON in both cases.
  1538. --
  1539. -- * Unicode surrogate pairs are now detected when decoding JSON.
  1540. --
  1541. -- 20100810.2 added some checking to ensure that an invalid Unicode character couldn't leak in to the UTF-8 encoding
  1542. --
  1543. -- 20100731.1 initial public release
  1544. --
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement