json_Tips.lua 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419
  1. -----------------------------------------------------------------------------
  2. -- JSON4Lua: JSON encoding / decoding support for the Lua language.
  3. -- json Module.
  4. -- Author: Craig Mason-Jones
  5. -- Homepage: http://json.luaforge.net/
  6. -- Version: 0.9.40
  7. -- This module is released under the MIT License (MIT).
  8. -- Please see LICENCE.txt for details.
  9. --
  10. -- USAGE:
  11. -- This module exposes two functions:
  12. -- encode(o)
  13. -- Returns the table / string / boolean / number / nil / json.null value as a JSON-encoded string.
  14. -- decode(json_string)
  15. -- Returns a Lua object populated with the data encoded in the JSON string json_string.
  16. --
  17. -- REQUIREMENTS:
  18. -- compat-5.1 if using Lua 5.0
  19. --
  20. -- CHANGELOG
  21. -- 0.9.20 Introduction of local Lua functions for private functions (removed _ function prefix).
  22. -- Fixed Lua 5.1 compatibility issues.
  23. -- Introduced json.null to have null values in associative arrays.
  24. -- encode() performance improvement (more than 50%) through table.concat rather than ..
  25. -- Introduced decode ability to ignore /**/ comments in the JSON string.
  26. -- 0.9.10 Fix to array encoding / decoding to correctly manage nil/null values in arrays.
  27. -----------------------------------------------------------------------------
  28. -----------------------------------------------------------------------------
  29. -- Imports and dependencies
  30. -----------------------------------------------------------------------------
  31. local math = require('math')
  32. local string = require("string")
  33. local table = require("table")
  34. local base = _G
  35. ---@class json
  36. json = {}
  37. -- Private functions
  38. local decode_scanArray
  39. local decode_scanComment
  40. local decode_scanConstant
  41. local decode_scanNumber
  42. local decode_scanObject
  43. local decode_scanString
  44. local decode_scanWhitespace
  45. local encodeString
  46. local isArray
  47. local isEncodable
  48. -----------------------------------------------------------------------------
  49. -- PUBLIC FUNCTIONS
  50. -----------------------------------------------------------------------------
  51. --- Encodes an arbitrary Lua object / variable.
  52. -- @param v The Lua object / variable to be JSON encoded.
  53. -- @return String containing the JSON encoding in internal Lua string format (i.e. not unicode)
  54. function json.encode (v)
  55. return cjson.encode(v)
  56. -- -- Handle nil values
  57. -- if v==nil then
  58. -- return "null"
  59. -- end
  60. --
  61. -- local vtype = base.type(v)
  62. --
  63. -- -- Handle strings
  64. -- if vtype=='string' then
  65. -- return '"' .. encodeString(v) .. '"' -- Need to handle encoding in string
  66. -- end
  67. --
  68. -- -- Handle booleans
  69. -- if vtype=='number' or vtype=='boolean' then
  70. -- return base.tostring(v)
  71. -- end
  72. --
  73. -- -- Handle tables
  74. -- if vtype=='table' then
  75. -----@class rval
  76. -- local rval = {}
  77. -- -- Consider arrays separately
  78. -- local bArray, maxCount = isArray(v)
  79. -- if bArray then
  80. -- for i = 1,maxCount do
  81. -- table.insert(rval, json.encode(v[i]))
  82. -- end
  83. -- else -- An object, not an array
  84. -- for i,j in base.pairs(v) do
  85. -- if isEncodable(i) and isEncodable(j) then
  86. -- table.insert(rval, '"' .. encodeString(i) .. '":' .. json.encode(j))
  87. -- end
  88. -- end
  89. -- end
  90. -- if bArray then
  91. -- return '[' .. table.concat(rval,',') ..']'
  92. -- else
  93. -- return '{' .. table.concat(rval,',') .. '}'
  94. -- end
  95. -- end
  96. --
  97. -- -- Handle null values
  98. -- if vtype=='function' and v==null then
  99. -- return 'null'
  100. -- end
  101. --
  102. -- base.assert(false,'encode attempt to encode unsupported type ' .. vtype .. ':' .. base.tostring(v))
  103. end
  104. --- Decodes a JSON string and returns the decoded value as a Lua data structure / value.
  105. -- @param s The string to scan.
  106. -- @param [startPos] Optional starting position where the JSON string is located. Defaults to 1.
  107. -- @param Lua object, number The object that was scanned, as a Lua table / string / number / boolean or nil,
  108. -- and the position of the first character after
  109. -- the scanned JSON object.
  110. function json.decode(s, startPos)
  111. return cjson.decode(s)
  112. --startPos = startPos and startPos or 1
  113. --startPos = decode_scanWhitespace(s,startPos)
  114. --base.assert(startPos<=string.len(s), 'Unterminated JSON encoded object found at position in [' .. s .. ']')
  115. --local curChar = string.sub(s,startPos,startPos)
  116. ---- Object
  117. --if curChar=='{' then
  118. -- return decode_scanObject(s,startPos)
  119. --end
  120. ---- Array
  121. --if curChar=='[' then
  122. -- return decode_scanArray(s,startPos)
  123. --end
  124. ---- Number
  125. --if string.find("+-0123456789.e", curChar, 1, true) then
  126. -- return decode_scanNumber(s,startPos)
  127. --end
  128. ---- String
  129. --if curChar==[["]] or curChar==[[']] then
  130. -- return decode_scanString(s,startPos)
  131. --end
  132. --if string.sub(s,startPos,startPos+1)=='/*' then
  133. -- return json.decode(s, decode_scanComment(s,startPos))
  134. --end
  135. ---- Otherwise, it must be a constant
  136. --return decode_scanConstant(s,startPos)
  137. end
  138. --- The null function allows one to specify a null value in an associative array (which is otherwise
  139. -- discarded if you set the value with 'nil' in Lua. Simply set t = { first=json.null }
  140. function json.null()
  141. return null -- so json.null() will also return null -)
  142. end
  143. -----------------------------------------------------------------------------
  144. -- Internal, PRIVATE functions.
  145. -- Following a Python-like convention, I have prefixed all these 'PRIVATE'
  146. -- functions with an underscore.
  147. -----------------------------------------------------------------------------
  148. --- Scans an array from JSON into a Lua object
  149. -- startPos begins at the start of the array.
  150. -- Returns the array and the next starting position
  151. -- @param s The string being scanned.
  152. -- @param startPos The starting position for the scan.
  153. -- @return table, int The scanned array as a table, and the position of the next character to scan.
  154. function decode_scanArray(s,startPos)
  155. ---@class array
  156. local array = {} -- The return value
  157. local stringLen = string.len(s)
  158. base.assert(string.sub(s,startPos,startPos)=='[','decode_scanArray called but array does not start at position ' .. startPos .. ' in string:\n'..s )
  159. startPos = startPos + 1
  160. -- Infinite loop for array elements
  161. repeat
  162. startPos = decode_scanWhitespace(s,startPos)
  163. base.assert(startPos<=stringLen,'JSON String ended unexpectedly scanning array.')
  164. local curChar = string.sub(s,startPos,startPos)
  165. if (curChar==']') then
  166. return array, startPos+1
  167. end
  168. if (curChar==',') then
  169. startPos = decode_scanWhitespace(s,startPos+1)
  170. end
  171. base.assert(startPos<=stringLen, 'JSON String ended unexpectedly scanning array.')
  172. object, startPos = json.decode(s,startPos)
  173. table.insert(array,object)
  174. until false
  175. end
  176. --- Scans a comment and discards the comment.
  177. -- Returns the position of the next character following the comment.
  178. -- @param string s The JSON string to scan.
  179. -- @param int startPos The starting position of the comment
  180. function decode_scanComment(s, startPos)
  181. base.assert( string.sub(s,startPos,startPos+1)=='/*', "decode_scanComment called but comment does not start at position " .. startPos)
  182. local endPos = string.find(s,'*/',startPos+2)
  183. base.assert(endPos~=nil, "Unterminated comment in string at " .. startPos)
  184. return endPos+2
  185. end
  186. --- Scans for given constants: true, false or null
  187. -- Returns the appropriate Lua type, and the position of the next character to read.
  188. -- @param s The string being scanned.
  189. -- @param startPos The position in the string at which to start scanning.
  190. -- @return object, int The object (true, false or nil) and the position at which the next character should be
  191. -- scanned.
  192. function decode_scanConstant(s, startPos)
  193. local consts = { ["true"] = true, ["false"] = false, ["null"] = nil }
  194. local constNames = {"true","false","null"}
  195. for i,k in base.pairs(constNames) do
  196. --print ("[" .. string.sub(s,startPos, startPos + string.len(k) -1) .."]", k)
  197. if string.sub(s,startPos, startPos + string.len(k) -1 )==k then
  198. return consts[k], startPos + string.len(k)
  199. end
  200. end
  201. base.assert(nil, 'Failed to scan constant from string ' .. s .. ' at starting position ' .. startPos)
  202. end
  203. --- Scans a number from the JSON encoded string.
  204. -- (in fact, also is able to scan numeric +- eqns, which is not
  205. -- in the JSON spec.)
  206. -- Returns the number, and the position of the next character
  207. -- after the number.
  208. -- @param s The string being scanned.
  209. -- @param startPos The position at which to start scanning.
  210. -- @return number, int The extracted number and the position of the next character to scan.
  211. function decode_scanNumber(s,startPos)
  212. local endPos = startPos+1
  213. local stringLen = string.len(s)
  214. local acceptableChars = "+-0123456789.e"
  215. while (string.find(acceptableChars, string.sub(s,endPos,endPos), 1, true)
  216. and endPos<=stringLen
  217. ) do
  218. endPos = endPos + 1
  219. end
  220. local stringValue = 'return ' .. string.sub(s,startPos, endPos-1)
  221. local stringEval = base.load(stringValue)
  222. base.assert(stringEval, 'Failed to scan number [ ' .. stringValue .. '] in JSON string at position ' .. startPos .. ' : ' .. endPos)
  223. return stringEval(), endPos
  224. end
  225. --- Scans a JSON object into a Lua object.
  226. -- startPos begins at the start of the object.
  227. -- Returns the object and the next starting position.
  228. -- @param s The string being scanned.
  229. -- @param startPos The starting position of the scan.
  230. -- @return table, int The scanned object as a table and the position of the next character to scan.
  231. function decode_scanObject(s,startPos)
  232. ---@class object
  233. local object = {}
  234. local stringLen = string.len(s)
  235. local key, value
  236. base.assert(string.sub(s,startPos,startPos)=='{','decode_scanObject called but object does not start at position ' .. startPos .. ' in string:\n' .. s)
  237. startPos = startPos + 1
  238. repeat
  239. startPos = decode_scanWhitespace(s,startPos)
  240. base.assert(startPos<=stringLen, 'JSON string ended unexpectedly while scanning object.')
  241. local curChar = string.sub(s,startPos,startPos)
  242. if (curChar=='}') then
  243. return object,startPos+1
  244. end
  245. if (curChar==',') then
  246. startPos = decode_scanWhitespace(s,startPos+1)
  247. end
  248. base.assert(startPos<=stringLen, 'JSON string ended unexpectedly scanning object.')
  249. -- Scan the key
  250. key, startPos = json.decode(s,startPos)
  251. base.assert(startPos<=stringLen, 'JSON string ended unexpectedly searching for value of key ' .. key)
  252. startPos = decode_scanWhitespace(s,startPos)
  253. base.assert(startPos<=stringLen, 'JSON string ended unexpectedly searching for value of key ' .. key)
  254. base.assert(string.sub(s,startPos,startPos)==':','JSON object key-value assignment mal-formed at ' .. startPos)
  255. startPos = decode_scanWhitespace(s,startPos+1)
  256. base.assert(startPos<=stringLen, 'JSON string ended unexpectedly searching for value of key ' .. key)
  257. value, startPos = json.decode(s,startPos)
  258. object[key]=value
  259. until false -- infinite loop while key-value pairs are found
  260. end
  261. -- START SoniEx2
  262. -- Initialize some things used by decode_scanString
  263. -- You know, for efficiency
  264. local escapeSequences = {
  265. ["\\t"] = "\t",
  266. ["\\f"] = "\f",
  267. ["\\r"] = "\r",
  268. ["\\n"] = "\n",
  269. ["\\b"] = "\b"
  270. }
  271. base.setmetatable(escapeSequences, {__index = function(t,k)
  272. -- skip "\" aka strip escape
  273. return string.sub(k,2)
  274. end})
  275. -- END SoniEx2
  276. --- Scans a JSON string from the opening inverted comma or single quote to the
  277. -- end of the string.
  278. -- Returns the string extracted as a Lua string,
  279. -- and the position of the next non-string character
  280. -- (after the closing inverted comma or single quote).
  281. -- @param s The string being scanned.
  282. -- @param startPos The starting position of the scan.
  283. -- @return string, int The extracted string as a Lua string, and the next character to parse.
  284. function decode_scanString(s,startPos)
  285. base.assert(startPos, 'decode_scanString(..) called without start position')
  286. local startChar = string.sub(s,startPos,startPos)
  287. -- START SoniEx2
  288. -- PS: I don't think single quotes are valid JSON
  289. base.assert(startChar == [["]] or startChar == [[']],'decode_scanString called for a non-string')
  290. --base.assert(startPos, "String decoding failed: missing closing " .. startChar .. " for string at position " .. oldStart)
  291. ---@class t
  292. local t = {}
  293. local i,j = startPos,startPos
  294. while string.find(s, startChar, j+1) ~= j+1 do
  295. local oldj = j
  296. i,j = string.find(s, "\\.", j+1)
  297. local x,y = string.find(s, startChar, oldj+1)
  298. if not i or x < i then
  299. --base.print(s, startPos, string.sub(s,startPos,oldj))
  300. i,j = x,y-1
  301. if not x then base.print(s, startPos, string.sub(s,startPos,oldj)) end
  302. end
  303. table.insert(t, string.sub(s, oldj+1, i-1))
  304. if string.sub(s, i, j) == "\\u" then
  305. local a = string.sub(s,j+1,j+4)
  306. j = j + 4
  307. local n = base.tonumber(a, 16)
  308. base.assert(n, "String decoding failed: bad Unicode escape " .. a .. " at position " .. i .. " : " .. j)
  309. -- math.floor(x/2^y) == lazy right shift
  310. -- a % 2^b == bitwise_and(a, (2^b)-1)
  311. -- 64 = 2^6
  312. -- 4096 = 2^12 (or 2^6 * 2^6)
  313. local x
  314. if n < 0x80 then
  315. x = string.char(n % 0x80)
  316. elseif n < 0x800 then
  317. -- [110x xxxx] [10xx xxxx]
  318. x = string.char(0xC0 + (math.floor(n/64) % 0x20), 0x80 + (n % 0x40))
  319. else
  320. -- [1110 xxxx] [10xx xxxx] [10xx xxxx]
  321. x = string.char(0xE0 + (math.floor(n/4096) % 0x10), 0x80 + (math.floor(n/64) % 0x40), 0x80 + (n % 0x40))
  322. end
  323. table.insert(t, x)
  324. else
  325. table.insert(t, escapeSequences[string.sub(s, i, j)])
  326. end
  327. end
  328. table.insert(t,string.sub(j, j+1))
  329. base.assert(string.find(s, startChar, j+1), "String decoding failed: missing closing " .. startChar .. " at position " .. j .. "(for string at position " .. startPos .. ")")
  330. return table.concat(t,""), j+2
  331. -- END SoniEx2
  332. end
  333. --- Scans a JSON string skipping all whitespace from the current start position.
  334. -- Returns the position of the first non-whitespace character, or nil if the whole end of string is reached.
  335. -- @param s The string being scanned
  336. -- @param startPos The starting position where we should begin removing whitespace.
  337. -- @return int The first position where non-whitespace was encountered, or string.len(s)+1 if the end of string
  338. -- was reached.
  339. function decode_scanWhitespace(s,startPos)
  340. local whitespace=" \n\r\t"
  341. local stringLen = string.len(s)
  342. while ( string.find(whitespace, string.sub(s,startPos,startPos), 1, true) and startPos <= stringLen) do
  343. startPos = startPos + 1
  344. end
  345. return startPos
  346. end
  347. --- Encodes a string to be JSON-compatible.
  348. -- This just involves back-quoting inverted commas, back-quotes and newlines, I think -)
  349. -- @param s The string to return as a JSON encoded (i.e. backquoted string)
  350. -- @return The string appropriately escaped.
  351. local escapeList = {
  352. ['"'] = '\\"',
  353. ['\\'] = '\\\\',
  354. ['/'] = '\\/',
  355. ['\b'] = '\\b',
  356. ['\f'] = '\\f',
  357. ['\n'] = '\\n',
  358. ['\r'] = '\\r',
  359. ['\t'] = '\\t'
  360. }
  361. function encodeString(s)
  362. return s:gsub(".", function(c) return escapeList[c] end) -- SoniEx2: 5.0 compat
  363. end
  364. -- Determines whether the given Lua type is an array or a table / dictionary.
  365. -- We consider any table an array if it has indexes 1..n for its n items, and no
  366. -- other data in the table.
  367. -- I think this method is currently a little 'flaky', but can't think of a good way around it yet...
  368. -- @param t The table to evaluate as an array
  369. -- @return boolean, number True if the table can be represented as an array, false otherwise. If true,
  370. -- the second returned value is the maximum
  371. -- number of indexed elements in the array.
  372. function isArray(t)
  373. -- Next we count all the elements, ensuring that any non-indexed elements are not-encodable
  374. -- (with the possible exception of 'n')
  375. local maxIndex = 0
  376. for k,v in base.pairs(t) do
  377. if (base.type(k)=='number' and math.floor(k)==k and 1<=k) then -- k,v is an indexed pair
  378. if (not isEncodable(v)) then return false end -- All array elements must be encodable
  379. maxIndex = math.max(maxIndex,k)
  380. else
  381. if (k=='n') then
  382. if v ~= table.getn(t) then return false end -- False if n does not hold the number of elements
  383. else -- Else of (k=='n')
  384. if isEncodable(v) then return false end
  385. end -- End of (k~='n')
  386. end -- End of k,v not an indexed pair
  387. end -- End of loop across all pairs
  388. return true, maxIndex
  389. end
  390. --- Determines whether the given Lua object / table / variable can be JSON encoded. The only
  391. -- types that are JSON encodable are: string, boolean, number, nil, table and json.null.
  392. -- In this implementation, all other types are ignored.
  393. -- @param o The object to examine.
  394. -- @return boolean True if the object should be JSON encoded, false if it should be ignored.
  395. function isEncodable(o)
  396. local t = base.type(o)
  397. return (t=='string' or t=='boolean' or t=='number' or t=='nil' or t=='table') or (t=='function' and o==null)
  398. end