Advertisement
Guest User

Untitled

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