Advertisement
william200027

Json

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