Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1490225
  • 博文数量: 129
  • 博客积分: 1449
  • 博客等级: 上尉
  • 技术积分: 3048
  • 用 户 组: 普通用户
  • 注册时间: 2012-07-24 18:36
文章分类

全部博文(129)

文章存档

2015年(3)

2014年(20)

2013年(65)

2012年(41)

分类: Python/Ruby

2014-07-31 08:47:24

1. 核心库json.lua

点击(此处)折叠或打开

  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.   
  63.   local vtype = base.type(v)

  64.   -- Handle strings
  65.   if vtype=='string' then
  66.     return '"' .. encodeString(v) .. '"'     -- Need to handle encoding in string
  67.   end
  68.   
  69.   -- Handle booleans
  70.   if vtype=='number' or vtype=='boolean' then
  71.     return base.tostring(v)
  72.   end
  73.   
  74.   -- Handle tables
  75.   if vtype=='table' then
  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, 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) .. '":' .. 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 decode(s, startPos)
  111.   startPos = startPos and startPos or 1
  112.   startPos = decode_scanWhitespace(s,startPos)
  113.   base.assert(startPos<=string.len(s), 'Unterminated JSON encoded object found at position in [' .. s .. ']')
  114.   local curChar = string.sub(s,startPos,startPos)
  115.   -- Object
  116.   if curChar=='{' then
  117.     return decode_scanObject(s,startPos)
  118.   end
  119.   -- Array
  120.   if curChar=='[' then
  121.     return decode_scanArray(s,startPos)
  122.   end
  123.   -- Number
  124.   if string.find("+-0123456789.e", curChar, 1, true) then
  125.     return decode_scanNumber(s,startPos)
  126.   end
  127.   -- String
  128.   if curChar==[["]] or curChar==[[']] then
  129.     return decode_scanString(s,startPos)
  130.   end
  131.   if string.sub(s,startPos,startPos+1)=='/*' then
  132.     return decode(s, decode_scanComment(s,startPos))
  133.   end
  134.   -- Otherwise, it must be a constant
  135.   return decode_scanConstant(s,startPos)
  136. end

  137. --- The null function allows one to specify a null value in an associative array (which is otherwise
  138. -- discarded if you set the value with 'nil' in Lua. Simply set t = { first=json.null }
  139. function null()
  140.   return null -- so json.null() will also return null ;-)
  141. end
  142. -----------------------------------------------------------------------------
  143. -- Internal, PRIVATE functions.
  144. -- Following a Python-like convention, I have prefixed all these 'PRIVATE'
  145. -- functions with an underscore.
  146. -----------------------------------------------------------------------------

  147. --- Scans an array from JSON into a Lua object
  148. -- startPos begins at the start of the array.
  149. -- Returns the array and the next starting position
  150. -- @param s The string being scanned.
  151. -- @param startPos The starting position for the scan.
  152. -- @return table, int The scanned array as a table, and the position of the next character to scan.
  153. function decode_scanArray(s,startPos)
  154.   local array = {}    -- The return value
  155.   local stringLen = string.len(s)
  156.   base.assert(string.sub(s,startPos,startPos)=='[','decode_scanArray called but array does not start at position ' .. startPos .. ' in string:\n'..s )
  157.   startPos = startPos + 1
  158.   -- Infinite loop for array elements
  159.   repeat
  160.     startPos = decode_scanWhitespace(s,startPos)
  161.     base.assert(startPos<=stringLen,'JSON String ended unexpectedly scanning array.')
  162.     local curChar = string.sub(s,startPos,startPos)
  163.     if (curChar==']') then
  164.       return array, startPos+1
  165.     end
  166.     if (curChar==',') then
  167.       startPos = decode_scanWhitespace(s,startPos+1)
  168.     end
  169.     base.assert(startPos<=stringLen, 'JSON String ended unexpectedly scanning array.')
  170.     object, startPos = decode(s,startPos)
  171.     table.insert(array,object)
  172.   until false
  173. end

  174. --- Scans a comment and discards the comment.
  175. -- Returns the position of the next character following the comment.
  176. -- @param string s The JSON string to scan.
  177. -- @param int startPos The starting position of the comment
  178. function decode_scanComment(s, startPos)
  179.   base.assert( string.sub(s,startPos,startPos+1)=='/*', "decode_scanComment called but comment does not start at position " .. startPos)
  180.   local endPos = string.find(s,'*/',startPos+2)
  181.   base.assert(endPos~=nil, "Unterminated comment in string at " .. startPos)
  182.   return endPos+2
  183. end

  184. --- Scans for given constants: true, false or null
  185. -- Returns the appropriate Lua type, and the position of the next character to read.
  186. -- @param s The string being scanned.
  187. -- @param startPos The position in the string at which to start scanning.
  188. -- @return object, int The object (true, false or nil) and the position at which the next character should be
  189. -- scanned.
  190. function decode_scanConstant(s, startPos)
  191.   local consts = { ["true"] = true, ["false"] = false, ["null"] = nil }
  192.   local constNames = {"true","false","null"}

  193.   for i,k in base.pairs(constNames) do
  194.     --print ("[" .. string.sub(s,startPos, startPos + string.len(k) -1) .."]", k)
  195.     if string.sub(s,startPos, startPos + string.len(k) -1 )==k then
  196.       return consts[k], startPos + string.len(k)
  197.     end
  198.   end
  199.   base.assert(nil, 'Failed to scan constant from string ' .. s .. ' at starting position ' .. startPos)
  200. end

  201. --- Scans a number from the JSON encoded string.
  202. -- (in fact, also is able to scan numeric +- eqns, which is not
  203. -- in the JSON spec.)
  204. -- Returns the number, and the position of the next character
  205. -- after the number.
  206. -- @param s The string being scanned.
  207. -- @param startPos The position at which to start scanning.
  208. -- @return number, int The extracted number and the position of the next character to scan.
  209. function decode_scanNumber(s,startPos)
  210.   local endPos = startPos+1
  211.   local stringLen = string.len(s)
  212.   local acceptableChars = "+-0123456789.e"
  213.   while (string.find(acceptableChars, string.sub(s,endPos,endPos), 1, true)
  214.     and endPos<=stringLen
  215.     ) do
  216.     endPos = endPos + 1
  217.   end
  218.   local stringValue = 'return ' .. string.sub(s,startPos, endPos-1)
  219.   local stringEval = base.loadstring(stringValue)
  220.   base.assert(stringEval, 'Failed to scan number [ ' .. stringValue .. '] in JSON string at position ' .. startPos .. ' : ' .. endPos)
  221.   return stringEval(), endPos
  222. end

  223. --- Scans a JSON object into a Lua object.
  224. -- startPos begins at the start of the object.
  225. -- Returns the object and the next starting position.
  226. -- @param s The string being scanned.
  227. -- @param startPos The starting position of the scan.
  228. -- @return table, int The scanned object as a table and the position of the next character to scan.
  229. function decode_scanObject(s,startPos)
  230.   local object = {}
  231.   local stringLen = string.len(s)
  232.   local key, value
  233.   base.assert(string.sub(s,startPos,startPos)=='{','decode_scanObject called but object does not start at position ' .. startPos .. ' in string:\n' .. s)
  234.   startPos = startPos + 1
  235.   repeat
  236.     startPos = decode_scanWhitespace(s,startPos)
  237.     base.assert(startPos<=stringLen, 'JSON string ended unexpectedly while scanning object.')
  238.     local curChar = string.sub(s,startPos,startPos)
  239.     if (curChar=='}') then
  240.       return object,startPos+1
  241.     end
  242.     if (curChar==',') then
  243.       startPos = decode_scanWhitespace(s,startPos+1)
  244.     end
  245.     base.assert(startPos<=stringLen, 'JSON string ended unexpectedly scanning object.')
  246.     -- Scan the key
  247.     key, startPos = decode(s,startPos)
  248.     base.assert(startPos<=stringLen, 'JSON string ended unexpectedly searching for value of key ' .. key)
  249.     startPos = decode_scanWhitespace(s,startPos)
  250.     base.assert(startPos<=stringLen, 'JSON string ended unexpectedly searching for value of key ' .. key)
  251.     base.assert(string.sub(s,startPos,startPos)==':','JSON object key-value assignment mal-formed at ' .. startPos)
  252.     startPos = decode_scanWhitespace(s,startPos+1)
  253.     base.assert(startPos<=stringLen, 'JSON string ended unexpectedly searching for value of key ' .. key)
  254.     value, startPos = decode(s,startPos)
  255.     object[key]=value
  256.   until false    -- infinite loop while key-value pairs are found
  257. end

  258. --- Scans a JSON string from the opening inverted comma or single quote to the
  259. -- end of the string.
  260. -- Returns the string extracted as a Lua string,
  261. -- and the position of the next non-string character
  262. -- (after the closing inverted comma or single quote).
  263. -- @param s The string being scanned.
  264. -- @param startPos The starting position of the scan.
  265. -- @return string, int The extracted string as a Lua string, and the next character to parse.
  266. function decode_scanString(s,startPos)
  267.   base.assert(startPos, 'decode_scanString(..) called without start position')
  268.   local startChar = string.sub(s,startPos,startPos)
  269.   base.assert(startChar==[[']] or startChar==[["]],'decode_scanString called for a non-string')
  270.   local escaped = false
  271.   local endPos = startPos + 1
  272.   local bEnded = false
  273.   local stringLen = string.len(s)
  274.   repeat
  275.     local curChar = string.sub(s,endPos,endPos)
  276.     -- Character escaping is only used to escape the string delimiters
  277.     if not escaped then    
  278.       if curChar==[[\]] then
  279.         escaped = true
  280.       else
  281.         bEnded = curChar==startChar
  282.       end
  283.     else
  284.       -- If we're escaped, we accept the current character come what may
  285.       escaped = false
  286.     end
  287.     endPos = endPos + 1
  288.     base.assert(endPos <= stringLen+1, "String decoding failed: unterminated string at position " .. endPos)
  289.   until bEnded
  290.   local stringValue = 'return ' .. string.sub(s, startPos, endPos-1)
  291.   local stringEval = base.loadstring(stringValue)
  292.   base.assert(stringEval, 'Failed to load string [ ' .. stringValue .. '] in JSON4Lua.decode_scanString at position ' .. startPos .. ' : ' .. endPos)
  293.   return stringEval(), endPos
  294. end

  295. --- Scans a JSON string skipping all whitespace from the current start position.
  296. -- Returns the position of the first non-whitespace character, or nil if the whole end of string is reached.
  297. -- @param s The string being scanned
  298. -- @param startPos The starting position where we should begin removing whitespace.
  299. -- @return int The first position where non-whitespace was encountered, or string.len(s)+1 if the end of string
  300. -- was reached.
  301. function decode_scanWhitespace(s,startPos)
  302.   local whitespace=" \n\r\t"
  303.   local stringLen = string.len(s)
  304.   while ( string.find(whitespace, string.sub(s,startPos,startPos), 1, true) and startPos <= stringLen) do
  305.     startPos = startPos + 1
  306.   end
  307.   return startPos
  308. end

  309. --- Encodes a string to be JSON-compatible.
  310. -- This just involves back-quoting inverted commas, back-quotes and newlines, I think ;-)
  311. -- @param s The string to return as a JSON encoded (i.e. backquoted string)
  312. -- @return The string appropriately escaped.
  313. function encodeString(s)
  314.   s = string.gsub(s,'\\','\\\\')
  315.   s = string.gsub(s,'"','\\"')
  316.   s = string.gsub(s,"'","\\'")
  317.   s = string.gsub(s,'\n','\\n')
  318.   s = string.gsub(s,'\t','\\t')
  319.   return s
  320. end

  321. -- Determines whether the given Lua type is an array or a table / dictionary.
  322. -- We consider any table an array if it has indexes 1..n for its n items, and no
  323. -- other data in the table.
  324. -- I think this method is currently a little 'flaky', but can't think of a good way around it yet...
  325. -- @param t The table to evaluate as an array
  326. -- @return boolean, number True if the table can be represented as an array, false otherwise. If true,
  327. -- the second returned value is the maximum
  328. -- number of indexed elements in the array.
  329. function isArray(t)
  330.   -- Next we count all the elements, ensuring that any non-indexed elements are not-encodable
  331.   -- (with the possible exception of 'n')
  332.   local maxIndex = 0
  333.   for k,v in base.pairs(t) do
  334.     if (base.type(k)=='number' and math.floor(k)==k and 1<=k) then    -- k,v is an indexed pair
  335.       if (not isEncodable(v)) then return false end    -- All array elements must be encodable
  336.       maxIndex = math.max(maxIndex,k)
  337.     else
  338.       if (k=='n') then
  339.         if v ~= table.getn(t) then return false end -- False if n does not hold the number of elements
  340.       else -- Else of (k=='n')
  341.         if isEncodable(v) then return false end
  342.       end -- End of (k~='n')
  343.     end -- End of k,v not an indexed pair
  344.   end -- End of loop across all pairs
  345.   return true, maxIndex
  346. end

  347. --- Determines whether the given Lua object / table / variable can be JSON encoded. The only
  348. -- types that are JSON encodable are: string, boolean, number, nil, table and json.null.
  349. -- In this implementation, all other types are ignored.
  350. -- @param o The object to examine.
  351. -- @return boolean True if the object should be JSON encoded, false if it should be ignored.
  352. function isEncodable(o)
  353.   local t = base.type(o)
  354.   return (t=='string' or t=='boolean' or t=='number' or t=='nil' or t=='table') or (t=='function' and o==null)
  355. end

2. 测试代码

点击(此处)折叠或打开

  1. --[[
  2. JSON4Lua example script.
  3. Demonstrates the simple functionality of the json module.
  4. ]]--
  5. -- json.lua在本目录下
  6. json = require('json')

  7. -- Object to JSON encode
  8. test = {
  9.   one='first', two='second', three={2,3,5}
  10. }

  11. jsonTest = json.encode(test)
  12. print('JSON encoded test is: ' .. jsonTest)
  13. -- JSON encoded test is: {"one":"first","three":[2,3,5],"two":"second"}

  14. -- Now JSON decode the json string
  15. result = json.decode(jsonTest)

  16. print ("The decoded table result:")
  17. table.foreach(result,print)
  18. print ("The decoded table result.three")
  19. table.foreach(result.three, print)

  20. -- 测试直接的json字符串, 不按字串中的顺序输出排列.
  21. json_str = '{"A":1, "B":2, "C":3, "D":4}'
  22. result = json.decode(json_str)

  23. for k,v in pairs(result) do
  24.     print(k..":"..v)
  25. end

3. 运行结果
JSON encoded test is: {"one":"first","three":[2,3,5],"two":"second"}
The decoded table result:
three   table: 0x8076ef8
one     first
two     second
The decoded table result.three
1       2
2       3
3       5
A:1
D:4
C:3
B:2


阅读(7051) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~