json.lua 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  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. -----------------------------------------------------------------------------
  36. -- Module declaration
  37. -----------------------------------------------------------------------------
  38. module("json")
  39. -- Public functions
  40. -- Private functions
  41. local decode_scanArray
  42. local decode_scanComment
  43. local decode_scanConstant
  44. local decode_scanNumber
  45. local decode_scanObject
  46. local decode_scanString
  47. local decode_scanWhitespace
  48. local encodeString
  49. local isArray
  50. local isEncodable
  51. -----------------------------------------------------------------------------
  52. -- PUBLIC FUNCTIONS
  53. -----------------------------------------------------------------------------
  54. --- Encodes an arbitrary Lua object / variable.
  55. -- @param v The Lua object / variable to be JSON encoded.
  56. -- @return String containing the JSON encoding in internal Lua string format (i.e. not unicode)
  57. function encode (v)
  58. -- Handle nil values
  59. if v==nil then
  60. return "null"
  61. end
  62. local vtype = base.type(v)
  63. -- Handle strings
  64. if vtype=='string' then
  65. return '"' .. encodeString(v) .. '"' -- Need to handle encoding in string
  66. end
  67. -- Handle booleans
  68. if vtype=='number' or vtype=='boolean' then
  69. return base.tostring(v)
  70. end
  71. -- Handle tables
  72. if vtype=='table' then
  73. local rval = {}
  74. -- Consider arrays separately
  75. local bArray, maxCount = isArray(v)
  76. if bArray then
  77. for i = 1,maxCount do
  78. table.insert(rval, encode(v[i]))
  79. end
  80. else -- An object, not an array
  81. for i,j in base.pairs(v) do
  82. if isEncodable(i) and isEncodable(j) then
  83. table.insert(rval, '"' .. encodeString(i) .. '":' .. encode(j))
  84. end
  85. end
  86. end
  87. if bArray then
  88. return '[' .. table.concat(rval,',') ..']'
  89. else
  90. return '{' .. table.concat(rval,',') .. '}'
  91. end
  92. end
  93. -- Handle null values
  94. if vtype=='function' and v==null then
  95. return 'null'
  96. end
  97. base.assert(false,'encode attempt to encode unsupported type ' .. vtype .. ':' .. base.tostring(v))
  98. end
  99. --- Decodes a JSON string and returns the decoded value as a Lua data structure / value.
  100. -- @param s The string to scan.
  101. -- @param [startPos] Optional starting position where the JSON string is located. Defaults to 1.
  102. -- @param Lua object, number The object that was scanned, as a Lua table / string / number / boolean or nil,
  103. -- and the position of the first character after
  104. -- the scanned JSON object.
  105. function decode(s, startPos)
  106. startPos = startPos and startPos or 1
  107. startPos = decode_scanWhitespace(s,startPos)
  108. base.assert(startPos<=string.len(s), 'Unterminated JSON encoded object found at position in [' .. s .. ']')
  109. local curChar = string.sub(s,startPos,startPos)
  110. -- Object
  111. if curChar=='{' then
  112. return decode_scanObject(s,startPos)
  113. end
  114. -- Array
  115. if curChar=='[' then
  116. return decode_scanArray(s,startPos)
  117. end
  118. -- Number
  119. if string.find("+-0123456789.e", curChar, 1, true) then
  120. return decode_scanNumber(s,startPos)
  121. end
  122. -- String
  123. if curChar==[["]] or curChar==[[']] then
  124. return decode_scanString(s,startPos)
  125. end
  126. if string.sub(s,startPos,startPos+1)=='/*' then
  127. return decode(s, decode_scanComment(s,startPos))
  128. end
  129. -- Otherwise, it must be a constant
  130. return decode_scanConstant(s,startPos)
  131. end
  132. --- The null function allows one to specify a null value in an associative array (which is otherwise
  133. -- discarded if you set the value with 'nil' in Lua. Simply set t = { first=json.null }
  134. function null()
  135. return null -- so json.null() will also return null ;-)
  136. end
  137. -----------------------------------------------------------------------------
  138. -- Internal, PRIVATE functions.
  139. -- Following a Python-like convention, I have prefixed all these 'PRIVATE'
  140. -- functions with an underscore.
  141. -----------------------------------------------------------------------------
  142. --- Scans an array from JSON into a Lua object
  143. -- startPos begins at the start of the array.
  144. -- Returns the array and the next starting position
  145. -- @param s The string being scanned.
  146. -- @param startPos The starting position for the scan.
  147. -- @return table, int The scanned array as a table, and the position of the next character to scan.
  148. function decode_scanArray(s,startPos)
  149. local array = {} -- The return value
  150. local stringLen = string.len(s)
  151. base.assert(string.sub(s,startPos,startPos)=='[','decode_scanArray called but array does not start at position ' .. startPos .. ' in string:\n'..s )
  152. startPos = startPos + 1
  153. -- Infinite loop for array elements
  154. repeat
  155. startPos = decode_scanWhitespace(s,startPos)
  156. base.assert(startPos<=stringLen,'JSON String ended unexpectedly scanning array.')
  157. local curChar = string.sub(s,startPos,startPos)
  158. if (curChar==']') then
  159. return array, startPos+1
  160. end
  161. if (curChar==',') then
  162. startPos = decode_scanWhitespace(s,startPos+1)
  163. end
  164. base.assert(startPos<=stringLen, 'JSON String ended unexpectedly scanning array.')
  165. object, startPos = decode(s,startPos)
  166. table.insert(array,object)
  167. until false
  168. end
  169. --- Scans a comment and discards the comment.
  170. -- Returns the position of the next character following the comment.
  171. -- @param string s The JSON string to scan.
  172. -- @param int startPos The starting position of the comment
  173. function decode_scanComment(s, startPos)
  174. base.assert( string.sub(s,startPos,startPos+1)=='/*', "decode_scanComment called but comment does not start at position " .. startPos)
  175. local endPos = string.find(s,'*/',startPos+2)
  176. base.assert(endPos~=nil, "Unterminated comment in string at " .. startPos)
  177. return endPos+2
  178. end
  179. --- Scans for given constants: true, false or null
  180. -- Returns the appropriate Lua type, and the position of the next character to read.
  181. -- @param s The string being scanned.
  182. -- @param startPos The position in the string at which to start scanning.
  183. -- @return object, int The object (true, false or nil) and the position at which the next character should be
  184. -- scanned.
  185. function decode_scanConstant(s, startPos)
  186. local consts = { ["true"] = true, ["false"] = false, ["null"] = nil }
  187. local constNames = {"true","false","null"}
  188. for i,k in base.pairs(constNames) do
  189. --print ("[" .. string.sub(s,startPos, startPos + string.len(k) -1) .."]", k)
  190. if string.sub(s,startPos, startPos + string.len(k) -1 )==k then
  191. return consts[k], startPos + string.len(k)
  192. end
  193. end
  194. base.assert(nil, 'Failed to scan constant from string ' .. s .. ' at starting position ' .. startPos)
  195. end
  196. --- Scans a number from the JSON encoded string.
  197. -- (in fact, also is able to scan numeric +- eqns, which is not
  198. -- in the JSON spec.)
  199. -- Returns the number, and the position of the next character
  200. -- after the number.
  201. -- @param s The string being scanned.
  202. -- @param startPos The position at which to start scanning.
  203. -- @return number, int The extracted number and the position of the next character to scan.
  204. function decode_scanNumber(s,startPos)
  205. local endPos = startPos+1
  206. local stringLen = string.len(s)
  207. local acceptableChars = "+-0123456789.e"
  208. while (string.find(acceptableChars, string.sub(s,endPos,endPos), 1, true)
  209. and endPos<=stringLen
  210. ) do
  211. endPos = endPos + 1
  212. end
  213. local stringValue = 'return ' .. string.sub(s,startPos, endPos-1)
  214. local stringEval = base.loadstring(stringValue)
  215. base.assert(stringEval, 'Failed to scan number [ ' .. stringValue .. '] in JSON string at position ' .. startPos .. ' : ' .. endPos)
  216. return stringEval(), endPos
  217. end
  218. --- Scans a JSON object into a Lua object.
  219. -- startPos begins at the start of the object.
  220. -- Returns the object and the next starting position.
  221. -- @param s The string being scanned.
  222. -- @param startPos The starting position of the scan.
  223. -- @return table, int The scanned object as a table and the position of the next character to scan.
  224. function decode_scanObject(s,startPos)
  225. local object = {}
  226. local stringLen = string.len(s)
  227. local key, value
  228. base.assert(string.sub(s,startPos,startPos)=='{','decode_scanObject called but object does not start at position ' .. startPos .. ' in string:\n' .. s)
  229. startPos = startPos + 1
  230. repeat
  231. startPos = decode_scanWhitespace(s,startPos)
  232. base.assert(startPos<=stringLen, 'JSON string ended unexpectedly while scanning object.')
  233. local curChar = string.sub(s,startPos,startPos)
  234. if (curChar=='}') then
  235. return object,startPos+1
  236. end
  237. if (curChar==',') then
  238. startPos = decode_scanWhitespace(s,startPos+1)
  239. end
  240. base.assert(startPos<=stringLen, 'JSON string ended unexpectedly scanning object.')
  241. -- Scan the key
  242. key, startPos = decode(s,startPos)
  243. base.assert(startPos<=stringLen, 'JSON string ended unexpectedly searching for value of key ' .. key)
  244. startPos = decode_scanWhitespace(s,startPos)
  245. base.assert(startPos<=stringLen, 'JSON string ended unexpectedly searching for value of key ' .. key)
  246. base.assert(string.sub(s,startPos,startPos)==':','JSON object key-value assignment mal-formed at ' .. startPos)
  247. startPos = decode_scanWhitespace(s,startPos+1)
  248. base.assert(startPos<=stringLen, 'JSON string ended unexpectedly searching for value of key ' .. key)
  249. value, startPos = decode(s,startPos)
  250. object[key]=value
  251. until false -- infinite loop while key-value pairs are found
  252. end
  253. --- Scans a JSON string from the opening inverted comma or single quote to the
  254. -- end of the string.
  255. -- Returns the string extracted as a Lua string,
  256. -- and the position of the next non-string character
  257. -- (after the closing inverted comma or single quote).
  258. -- @param s The string being scanned.
  259. -- @param startPos The starting position of the scan.
  260. -- @return string, int The extracted string as a Lua string, and the next character to parse.
  261. function decode_scanString(s,startPos)
  262. base.assert(startPos, 'decode_scanString(..) called without start position')
  263. local startChar = string.sub(s,startPos,startPos)
  264. base.assert(startChar==[[']] or startChar==[["]],'decode_scanString called for a non-string')
  265. local escaped = false
  266. local endPos = startPos + 1
  267. local bEnded = false
  268. local stringLen = string.len(s)
  269. repeat
  270. local curChar = string.sub(s,endPos,endPos)
  271. -- Character escaping is only used to escape the string delimiters
  272. if not escaped then
  273. if curChar==[[\]] then
  274. escaped = true
  275. else
  276. bEnded = curChar==startChar
  277. end
  278. else
  279. -- If we're escaped, we accept the current character come what may
  280. escaped = false
  281. end
  282. endPos = endPos + 1
  283. base.assert(endPos <= stringLen+1, "String decoding failed: unterminated string at position " .. endPos)
  284. until bEnded
  285. local stringValue = 'return ' .. string.sub(s, startPos, endPos-1)
  286. local stringEval = base.loadstring(stringValue)
  287. base.assert(stringEval, 'Failed to load string [ ' .. stringValue .. '] in JSON4Lua.decode_scanString at position ' .. startPos .. ' : ' .. endPos)
  288. return stringEval(), endPos
  289. end
  290. --- Scans a JSON string skipping all whitespace from the current start position.
  291. -- Returns the position of the first non-whitespace character, or nil if the whole end of string is reached.
  292. -- @param s The string being scanned
  293. -- @param startPos The starting position where we should begin removing whitespace.
  294. -- @return int The first position where non-whitespace was encountered, or string.len(s)+1 if the end of string
  295. -- was reached.
  296. function decode_scanWhitespace(s,startPos)
  297. local whitespace=" \n\r\t"
  298. local stringLen = string.len(s)
  299. while ( string.find(whitespace, string.sub(s,startPos,startPos), 1, true) and startPos <= stringLen) do
  300. startPos = startPos + 1
  301. end
  302. return startPos
  303. end
  304. --- Encodes a string to be JSON-compatible.
  305. -- This just involves back-quoting inverted commas, back-quotes and newlines, I think ;-)
  306. -- @param s The string to return as a JSON encoded (i.e. backquoted string)
  307. -- @return The string appropriately escaped.
  308. function encodeString(s)
  309. s = string.gsub(s,'\\','\\\\')
  310. s = string.gsub(s,'"','\\"')
  311. s = string.gsub(s,"'","\\'")
  312. s = string.gsub(s,'\r','\\r')
  313. s = string.gsub(s,'\n','\\n')
  314. s = string.gsub(s,'\t','\\t')
  315. return s
  316. end
  317. -- Determines whether the given Lua type is an array or a table / dictionary.
  318. -- We consider any table an array if it has indexes 1..n for its n items, and no
  319. -- other data in the table.
  320. -- I think this method is currently a little 'flaky', but can't think of a good way around it yet...
  321. -- @param t The table to evaluate as an array
  322. -- @return boolean, number True if the table can be represented as an array, false otherwise. If true,
  323. -- the second returned value is the maximum
  324. -- number of indexed elements in the array.
  325. function isArray(t)
  326. -- Next we count all the elements, ensuring that any non-indexed elements are not-encodable
  327. -- (with the possible exception of 'n')
  328. local maxIndex = 0
  329. for k,v in base.pairs(t) do
  330. if (base.type(k)=='number' and math.floor(k)==k and 1<=k) then -- k,v is an indexed pair
  331. if (not isEncodable(v)) then return false end -- All array elements must be encodable
  332. maxIndex = math.max(maxIndex,k)
  333. else
  334. if (k=='n') then
  335. if v ~= table.getn(t) then return false end -- False if n does not hold the number of elements
  336. else -- Else of (k=='n')
  337. if isEncodable(v) then return false end
  338. end -- End of (k~='n')
  339. end -- End of k,v not an indexed pair
  340. end -- End of loop across all pairs
  341. return true, maxIndex
  342. end
  343. --- Determines whether the given Lua object / table / variable can be JSON encoded. The only
  344. -- types that are JSON encodable are: string, boolean, number, nil, table and json.null.
  345. -- In this implementation, all other types are ignored.
  346. -- @param o The object to examine.
  347. -- @return boolean True if the object should be JSON encoded, false if it should be ignored.
  348. function isEncodable(o)
  349. local t = base.type(o)
  350. return (t=='string' or t=='boolean' or t=='number' or t=='nil' or t=='table') or (t=='function' and o==null)
  351. end