manual.txt 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613
  1. = Lua CJSON 2.1devel Manual =
  2. Mark Pulford <mark@kyne.com.au>
  3. :revdate: 1st March 2012
  4. Overview
  5. --------
  6. The Lua CJSON module provides JSON support for Lua.
  7. *Features*::
  8. - Fast, standards compliant encoding/parsing routines
  9. - Full support for JSON with UTF-8, including decoding surrogate pairs
  10. - Optional run-time support for common exceptions to the JSON
  11. specification (infinity, NaN,..)
  12. - No dependencies on other libraries
  13. *Caveats*::
  14. - UTF-16 and UTF-32 are not supported
  15. Lua CJSON is covered by the MIT license. Review the file +LICENSE+ for
  16. details.
  17. The latest version of this software is available from the
  18. http://www.kyne.com.au/%7Emark/software/lua-cjson.php[Lua CJSON website].
  19. Feel free to email me if you have any patches, suggestions, or comments.
  20. Installation
  21. ------------
  22. Lua CJSON requires either http://www.lua.org[Lua] 5.1, Lua 5.2, or
  23. http://www.luajit.org[LuaJIT] to build.
  24. The build method can be selected from 4 options:
  25. Make:: Unix (including Linux, BSD, Mac OSX & Solaris), Windows
  26. CMake:: Unix, Windows
  27. RPM:: Linux
  28. LuaRocks:: Unix, Windows
  29. Make
  30. ~~~~
  31. The included +Makefile+ has generic settings.
  32. First, review and update the included makefile to suit your platform (if
  33. required).
  34. Next, build and install the module:
  35. [source,sh]
  36. make install
  37. Or install manually into your Lua module directory:
  38. [source,sh]
  39. make
  40. cp cjson.so $LUA_MODULE_DIRECTORY
  41. CMake
  42. ~~~~~
  43. http://www.cmake.org[CMake] can generate build configuration for many
  44. different platforms (including Unix and Windows).
  45. First, generate the makefile for your platform using CMake. If CMake is
  46. unable to find Lua, manually set the +LUA_DIR+ environment variable to
  47. the base prefix of your Lua 5.1 installation.
  48. While +cmake+ is used in the example below, +ccmake+ or +cmake-gui+ may
  49. be used to present an interface for changing the default build options.
  50. [source,sh]
  51. mkdir build
  52. cd build
  53. # Optional: export LUA_DIR=$LUA51_PREFIX
  54. cmake ..
  55. Next, build and install the module:
  56. [source,sh]
  57. make install
  58. # Or:
  59. make
  60. cp cjson.so $LUA_MODULE_DIRECTORY
  61. Review the
  62. http://www.cmake.org/cmake/help/documentation.html[CMake documentation]
  63. for further details.
  64. RPM
  65. ~~~
  66. Linux distributions using http://rpm.org[RPM] can create a package via
  67. the included RPM spec file. Ensure the +rpm-build+ package (or similar)
  68. has been installed.
  69. Build and install the module via RPM:
  70. [source,sh]
  71. rpmbuild -tb lua-cjson-2.1devel.tar.gz
  72. rpm -Uvh $LUA_CJSON_RPM
  73. LuaRocks
  74. ~~~~~~~~
  75. http://luarocks.org[LuaRocks] can be used to install and manage Lua
  76. modules on a wide range of platforms (including Windows).
  77. First, extract the Lua CJSON source package.
  78. Next, install the module:
  79. [source,sh]
  80. cd lua-cjson-2.1devel
  81. luarocks make
  82. [NOTE]
  83. LuaRocks does not support platform specific configuration for Solaris.
  84. On Solaris, you may need to manually uncomment +USE_INTERNAL_ISINF+ in
  85. the rockspec before building this module.
  86. Review the http://luarocks.org/en/Documentation[LuaRocks documentation]
  87. for further details.
  88. [[build_options]]
  89. Build Options (#define)
  90. ~~~~~~~~~~~~~~~~~~~~~~~
  91. Lua CJSON offers several +#define+ build options to address portability
  92. issues, and enable non-default features. Some build methods may
  93. automatically set platform specific options if required. Other features
  94. should be enabled manually.
  95. USE_INTERNAL_ISINF:: Workaround for Solaris platforms missing +isinf+.
  96. DISABLE_INVALID_NUMBERS:: Recommended on platforms where +strtod+ /
  97. +sprintf+ are not POSIX compliant (eg, Windows MinGW). Prevents
  98. +cjson.encode_invalid_numbers+ and +cjson.decode_invalid_numbers+ from
  99. being enabled. However, +cjson.encode_invalid_numbers+ may still be
  100. set to +"null"+. When using the Lua CJSON built-in floating point
  101. conversion this option is unnecessary and is ignored.
  102. Built-in floating point conversion
  103. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  104. Lua CJSON may be built with David Gay's
  105. http://www.netlib.org/fp/[floating point conversion routines]. This can
  106. increase overall performance by up to 50% on some platforms when
  107. converting a large amount of numeric data. However, this option reduces
  108. portability and is disabled by default.
  109. USE_INTERNAL_FPCONV:: Enable internal number conversion routines.
  110. IEEE_BIG_ENDIAN:: Must be set on big endian architectures.
  111. MULTIPLE_THREADS:: Must be set if Lua CJSON may be used in a
  112. multi-threaded application. Requires the _pthreads_ library.
  113. API (Functions)
  114. ---------------
  115. Synopsis
  116. ~~~~~~~~
  117. [source,lua]
  118. ------------
  119. -- Module instantiation
  120. local cjson = require "cjson"
  121. local cjson2 = cjson.new()
  122. local cjson_safe = require "cjson.safe"
  123. -- Translate Lua value to/from JSON
  124. text = cjson.encode(value)
  125. value = cjson.decode(text)
  126. -- Get and/or set Lua CJSON configuration
  127. setting = cjson.decode_invalid_numbers([setting])
  128. setting = cjson.encode_invalid_numbers([setting])
  129. keep = cjson.encode_keep_buffer([keep])
  130. depth = cjson.encode_max_depth([depth])
  131. depth = cjson.decode_max_depth([depth])
  132. convert, ratio, safe = cjson.encode_sparse_array([convert[, ratio[, safe]]])
  133. ------------
  134. Module Instantiation
  135. ~~~~~~~~~~~~~~~~~~~~
  136. [source,lua]
  137. ------------
  138. local cjson = require "cjson"
  139. local cjson2 = cjson.new()
  140. local cjson_safe = require "cjson.safe"
  141. ------------
  142. Import Lua CJSON via the Lua +require+ function. Lua CJSON does not
  143. register a global module table.
  144. The +cjson+ module will throw an error during JSON conversion if any
  145. invalid data is encountered. Refer to <<cjson_encode,+cjson.encode+>>
  146. and <<cjson_decode,+cjson.decode+>> for details.
  147. The +cjson.safe+ module behaves identically to the +cjson+ module,
  148. except when errors are encountered during JSON conversion. On error, the
  149. +cjson_safe.encode+ and +cjson_safe.decode+ functions will return
  150. +nil+ followed by the error message.
  151. +cjson.new+ can be used to instantiate an independent copy of the Lua
  152. CJSON module. The new module has a separate persistent encoding buffer,
  153. and default settings.
  154. Lua CJSON can support Lua implementations using multiple preemptive
  155. threads within a single Lua state provided the persistent encoding
  156. buffer is not shared. This can be achieved by one of the following
  157. methods:
  158. - Disabling the persistent encoding buffer with
  159. <<encode_keep_buffer,+cjson.encode_keep_buffer+>>
  160. - Ensuring each thread calls <<encode,+cjson.encode+>> separately (ie,
  161. treat +cjson.encode+ as non-reentrant).
  162. - Using a separate +cjson+ module table per preemptive thread
  163. (+cjson.new+)
  164. [NOTE]
  165. Lua CJSON uses +strtod+ and +snprintf+ to perform numeric conversion as
  166. they are usually well supported, fast and bug free. However, these
  167. functions require a workaround for JSON encoding/parsing under locales
  168. using a comma decimal separator. Lua CJSON detects the current locale
  169. during instantiation to determine and automatically implement the
  170. workaround if required. Lua CJSON should be reinitialised via
  171. +cjson.new+ if the locale of the current process changes. Using a
  172. different locale per thread is not supported.
  173. decode
  174. ~~~~~~
  175. [source,lua]
  176. ------------
  177. value = cjson.decode(json_text)
  178. ------------
  179. +cjson.decode+ will deserialise any UTF-8 JSON string into a Lua value
  180. or table.
  181. UTF-16 and UTF-32 JSON strings are not supported.
  182. +cjson.decode+ requires that any NULL (ASCII 0) and double quote (ASCII
  183. 34) characters are escaped within strings. All escape codes will be
  184. decoded and other bytes will be passed transparently. UTF-8 characters
  185. are not validated during decoding and should be checked elsewhere if
  186. required.
  187. JSON +null+ will be converted to a NULL +lightuserdata+ value. This can
  188. be compared with +cjson.null+ for convenience.
  189. By default, numbers incompatible with the JSON specification (infinity,
  190. NaN, hexadecimal) can be decoded. This default can be changed with
  191. <<decode_invalid_numbers,+cjson.decode_invalid_numbers+>>.
  192. .Example: Decoding
  193. [source,lua]
  194. json_text = '[ true, { "foo": "bar" } ]'
  195. value = cjson.decode(json_text)
  196. -- Returns: { true, { foo = "bar" } }
  197. [CAUTION]
  198. Care must be taken after decoding JSON objects with numeric keys. Each
  199. numeric key will be stored as a Lua +string+. Any subsequent code
  200. assuming type +number+ may break.
  201. [[decode_invalid_numbers]]
  202. decode_invalid_numbers
  203. ~~~~~~~~~~~~~~~~~~~~~~
  204. [source,lua]
  205. ------------
  206. setting = cjson.decode_invalid_numbers([setting])
  207. -- "setting" must be a boolean. Default: true.
  208. ------------
  209. Lua CJSON may generate an error when trying to decode numbers not
  210. supported by the JSON specification. _Invalid numbers_ are defined as:
  211. - infinity
  212. - NaN
  213. - hexadecimal
  214. Available settings:
  215. +true+:: Accept and decode _invalid numbers_. This is the default
  216. setting.
  217. +false+:: Throw an error when _invalid numbers_ are encountered.
  218. The current setting is always returned, and is only updated when an
  219. argument is provided.
  220. [[decode_max_depth]]
  221. decode_max_depth
  222. ~~~~~~~~~~~~~~~~
  223. [source,lua]
  224. ------------
  225. depth = cjson.decode_max_depth([depth])
  226. -- "depth" must be a positive integer. Default: 1000.
  227. ------------
  228. Lua CJSON will generate an error when parsing deeply nested JSON once
  229. the maximum array/object depth has been exceeded. This check prevents
  230. unnecessarily complicated JSON from slowing down the application, or
  231. crashing the application due to lack of process stack space.
  232. An error may be generated before the depth limit is hit if Lua is unable
  233. to allocate more objects on the Lua stack.
  234. By default, Lua CJSON will reject JSON with arrays and/or objects nested
  235. more than 1000 levels deep.
  236. The current setting is always returned, and is only updated when an
  237. argument is provided.
  238. [[encode]]
  239. encode
  240. ~~~~~~
  241. [source,lua]
  242. ------------
  243. json_text = cjson.encode(value)
  244. ------------
  245. +cjson.encode+ will serialise a Lua value into a string containing the
  246. JSON representation.
  247. +cjson.encode+ supports the following types:
  248. - +boolean+
  249. - +lightuserdata+ (NULL value only)
  250. - +nil+
  251. - +number+
  252. - +string+
  253. - +table+
  254. The remaining Lua types will generate an error:
  255. - +function+
  256. - +lightuserdata+ (non-NULL values)
  257. - +thread+
  258. - +userdata+
  259. By default, numbers are encoded with 14 significant digits. Refer to
  260. <<encode_number_precision,+cjson.encode_number_precision+>> for details.
  261. Lua CJSON will escape the following characters within each UTF-8 string:
  262. - Control characters (ASCII 0 - 31)
  263. - Double quote (ASCII 34)
  264. - Forward slash (ASCII 47)
  265. - Blackslash (ASCII 92)
  266. - Delete (ASCII 127)
  267. All other bytes are passed transparently.
  268. [CAUTION]
  269. =========
  270. Lua CJSON will successfully encode/decode binary strings, but this is
  271. technically not supported by JSON and may not be compatible with other
  272. JSON libraries. To ensure the output is valid JSON, applications should
  273. ensure all Lua strings passed to +cjson.encode+ are UTF-8.
  274. Base64 is commonly used to encode binary data as the most efficient
  275. encoding under UTF-8 can only reduce the encoded size by a further
  276. &#126;8%. Lua Base64 routines can be found in the
  277. http://w3.impa.br/%7Ediego/software/luasocket/[LuaSocket] and
  278. http://www.tecgraf.puc-rio.br/%7Elhf/ftp/lua/#lbase64[lbase64] packages.
  279. =========
  280. Lua CJSON uses a heuristic to determine whether to encode a Lua table as
  281. a JSON array or an object. A Lua table with only positive integer keys
  282. of type +number+ will be encoded as a JSON array. All other tables will
  283. be encoded as a JSON object.
  284. Lua CJSON does not use metamethods when serialising tables.
  285. - +rawget+ is used to iterate over Lua arrays
  286. - +next+ is used to iterate over Lua objects
  287. Lua arrays with missing entries (_sparse arrays_) may optionally be
  288. encoded in several different ways. Refer to
  289. <<encode_sparse_array,+cjson.encode_sparse_array+>> for details.
  290. JSON object keys are always strings. Hence +cjson.encode+ only supports
  291. table keys which are type +number+ or +string+. All other types will
  292. generate an error.
  293. [NOTE]
  294. Standards compliant JSON must be encapsulated in either an object (+{}+)
  295. or an array (+[]+). If strictly standards compliant JSON is desired, a
  296. table must be passed to +cjson.encode+.
  297. By default, encoding the following Lua values will generate errors:
  298. - Numbers incompatible with the JSON specification (infinity, NaN)
  299. - Tables nested more than 1000 levels deep
  300. - Excessively sparse Lua arrays
  301. These defaults can be changed with:
  302. - <<encode_invalid_numbers,+cjson.encode_invalid_numbers+>>
  303. - <<encode_max_depth,+cjson.encode_max_depth+>>
  304. - <<encode_sparse_array,+cjson.encode_sparse_array+>>
  305. .Example: Encoding
  306. [source,lua]
  307. value = { true, { foo = "bar" } }
  308. json_text = cjson.encode(value)
  309. -- Returns: '[true,{"foo":"bar"}]'
  310. [[encode_invalid_numbers]]
  311. encode_invalid_numbers
  312. ~~~~~~~~~~~~~~~~~~~~~~
  313. [source,lua]
  314. ------------
  315. setting = cjson.encode_invalid_numbers([setting])
  316. -- "setting" must a boolean or "null". Default: false.
  317. ------------
  318. Lua CJSON may generate an error when encoding floating point numbers not
  319. supported by the JSON specification (_invalid numbers_):
  320. - infinity
  321. - NaN
  322. Available settings:
  323. +true+:: Allow _invalid numbers_ to be encoded using the Javascript
  324. compatible values +NaN+ and +Infinity+. This will generate
  325. non-standard JSON, but these values are supported by some libraries.
  326. +"null"+:: Encode _invalid numbers_ as a JSON +null+ value. This allows
  327. infinity and NaN to be encoded into valid JSON.
  328. +false+:: Throw an error when attempting to encode _invalid numbers_.
  329. This is the default setting.
  330. The current setting is always returned, and is only updated when an
  331. argument is provided.
  332. [[encode_keep_buffer]]
  333. encode_keep_buffer
  334. ~~~~~~~~~~~~~~~~~~
  335. [source,lua]
  336. ------------
  337. keep = cjson.encode_keep_buffer([keep])
  338. -- "keep" must be a boolean. Default: true.
  339. ------------
  340. Lua CJSON can reuse the JSON encoding buffer to improve performance.
  341. Available settings:
  342. +true+:: The buffer will grow to the largest size required and is not
  343. freed until the Lua CJSON module is garbage collected. This is the
  344. default setting.
  345. +false+:: Free the encode buffer after each call to +cjson.encode+.
  346. The current setting is always returned, and is only updated when an
  347. argument is provided.
  348. [[encode_max_depth]]
  349. encode_max_depth
  350. ~~~~~~~~~~~~~~~~
  351. [source,lua]
  352. ------------
  353. depth = cjson.encode_max_depth([depth])
  354. -- "depth" must be a positive integer. Default: 1000.
  355. ------------
  356. Once the maximum table depth has been exceeded Lua CJSON will generate
  357. an error. This prevents a deeply nested or recursive data structure from
  358. crashing the application.
  359. By default, Lua CJSON will generate an error when trying to encode data
  360. structures with more than 1000 nested tables.
  361. The current setting is always returned, and is only updated when an
  362. argument is provided.
  363. .Example: Recursive Lua table
  364. [source,lua]
  365. a = {}; a[1] = a
  366. [[encode_number_precision]]
  367. encode_number_precision
  368. ~~~~~~~~~~~~~~~~~~~~~~~
  369. [source,lua]
  370. ------------
  371. precision = cjson.encode_number_precision([precision])
  372. -- "precision" must be an integer between 1 and 14. Default: 14.
  373. ------------
  374. The amount of significant digits returned by Lua CJSON when encoding
  375. numbers can be changed to balance accuracy versus performance. For data
  376. structures containing many numbers, setting
  377. +cjson.encode_number_precision+ to a smaller integer, for example +3+,
  378. can improve encoding performance by up to 50%.
  379. By default, Lua CJSON will output 14 significant digits when converting
  380. a number to text.
  381. The current setting is always returned, and is only updated when an
  382. argument is provided.
  383. [[encode_sparse_array]]
  384. encode_sparse_array
  385. ~~~~~~~~~~~~~~~~~~~
  386. [source,lua]
  387. ------------
  388. convert, ratio, safe = cjson.encode_sparse_array([convert[, ratio[, safe]]])
  389. -- "convert" must be a boolean. Default: false.
  390. -- "ratio" must be a positive integer. Default: 2.
  391. -- "safe" must be a positive integer. Default: 10.
  392. ------------
  393. Lua CJSON classifies a Lua table into one of three kinds when encoding a
  394. JSON array. This is determined by the number of values missing from the
  395. Lua array as follows:
  396. Normal:: All values are available.
  397. Sparse:: At least 1 value is missing.
  398. Excessively sparse:: The number of values missing exceeds the configured
  399. ratio.
  400. Lua CJSON encodes sparse Lua arrays as JSON arrays using JSON +null+ for
  401. the missing entries.
  402. An array is excessively sparse when all the following conditions are
  403. met:
  404. - +ratio+ > +0+
  405. - _maximum_index_ > +safe+
  406. - _maximum_index_ > _item_count_ * +ratio+
  407. Lua CJSON will never consider an array to be _excessively sparse_ when
  408. +ratio+ = +0+. The +safe+ limit ensures that small Lua arrays are always
  409. encoded as sparse arrays.
  410. By default, attempting to encode an _excessively sparse_ array will
  411. generate an error. If +convert+ is set to +true+, _excessively sparse_
  412. arrays will be converted to a JSON object.
  413. The current settings are always returned. A particular setting is only
  414. changed when the argument is provided (non-++nil++).
  415. .Example: Encoding a sparse array
  416. [source,lua]
  417. cjson.encode({ [3] = "data" })
  418. -- Returns: '[null,null,"data"]'
  419. .Example: Enabling conversion to a JSON object
  420. [source,lua]
  421. cjson.encode_sparse_array(true)
  422. cjson.encode({ [1000] = "excessively sparse" })
  423. -- Returns: '{"1000":"excessively sparse"}'
  424. API (Variables)
  425. ---------------
  426. _NAME
  427. ~~~~~
  428. The name of the Lua CJSON module (+"cjson"+).
  429. _VERSION
  430. ~~~~~~~~
  431. The version number of the Lua CJSON module (+"2.1devel"+).
  432. null
  433. ~~~~
  434. Lua CJSON decodes JSON +null+ as a Lua +lightuserdata+ NULL pointer.
  435. +cjson.null+ is provided for comparison.
  436. [sect1]
  437. References
  438. ----------
  439. - http://tools.ietf.org/html/rfc4627[RFC 4627]
  440. - http://www.json.org/[JSON website]
  441. // vi:ft=asciidoc tw=72: