manual.adoc 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613
  1. = Lua CJSON 2.1devel Manual =
  2. Mark Pulford <[email protected]>
  3. :revdate: August 2016
  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 current stable 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, Lua 5.3,
  23. or 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 <<encode,+cjson.encode+>> and
  146. <<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. decode
  175. ~~~~~~
  176. [source,lua]
  177. ------------
  178. value = cjson.decode(json_text)
  179. ------------
  180. +cjson.decode+ will deserialise any UTF-8 JSON string into a Lua value
  181. or table.
  182. UTF-16 and UTF-32 JSON strings are not supported.
  183. +cjson.decode+ requires that any NULL (ASCII 0) and double quote (ASCII
  184. 34) characters are escaped within strings. All escape codes will be
  185. decoded and other bytes will be passed transparently. UTF-8 characters
  186. are not validated during decoding and should be checked elsewhere if
  187. required.
  188. JSON +null+ will be converted to a NULL +lightuserdata+ value. This can
  189. be compared with +cjson.null+ for convenience.
  190. By default, numbers incompatible with the JSON specification (infinity,
  191. NaN, hexadecimal) can be decoded. This default can be changed with
  192. <<decode_invalid_numbers,+cjson.decode_invalid_numbers+>>.
  193. .Example: Decoding
  194. [source,lua]
  195. json_text = '[ true, { "foo": "bar" } ]'
  196. value = cjson.decode(json_text)
  197. -- Returns: { true, { foo = "bar" } }
  198. [CAUTION]
  199. Care must be taken after decoding JSON objects with numeric keys. Each
  200. numeric key will be stored as a Lua +string+. Any subsequent code
  201. assuming type +number+ may break.
  202. [[decode_invalid_numbers]]
  203. decode_invalid_numbers
  204. ~~~~~~~~~~~~~~~~~~~~~~
  205. [source,lua]
  206. ------------
  207. setting = cjson.decode_invalid_numbers([setting])
  208. -- "setting" must be a boolean. Default: true.
  209. ------------
  210. Lua CJSON may generate an error when trying to decode numbers not
  211. supported by the JSON specification. _Invalid numbers_ are defined as:
  212. - infinity
  213. - NaN
  214. - hexadecimal
  215. Available settings:
  216. +true+:: Accept and decode _invalid numbers_. This is the default
  217. setting.
  218. +false+:: Throw an error when _invalid numbers_ are encountered.
  219. The current setting is always returned, and is only updated when an
  220. argument is provided.
  221. [[decode_max_depth]]
  222. decode_max_depth
  223. ~~~~~~~~~~~~~~~~
  224. [source,lua]
  225. ------------
  226. depth = cjson.decode_max_depth([depth])
  227. -- "depth" must be a positive integer. Default: 1000.
  228. ------------
  229. Lua CJSON will generate an error when parsing deeply nested JSON once
  230. the maximum array/object depth has been exceeded. This check prevents
  231. unnecessarily complicated JSON from slowing down the application, or
  232. crashing the application due to lack of process stack space.
  233. An error may be generated before the depth limit is hit if Lua is unable
  234. to allocate more objects on the Lua stack.
  235. By default, Lua CJSON will reject JSON with arrays and/or objects nested
  236. more than 1000 levels deep.
  237. The current setting is always returned, and is only updated when an
  238. argument is provided.
  239. [[encode]]
  240. encode
  241. ~~~~~~
  242. [source,lua]
  243. ------------
  244. json_text = cjson.encode(value)
  245. ------------
  246. +cjson.encode+ will serialise a Lua value into a string containing the
  247. JSON representation.
  248. +cjson.encode+ supports the following types:
  249. - +boolean+
  250. - +lightuserdata+ (NULL value only)
  251. - +nil+
  252. - +number+
  253. - +string+
  254. - +table+
  255. The remaining Lua types will generate an error:
  256. - +function+
  257. - +lightuserdata+ (non-NULL values)
  258. - +thread+
  259. - +userdata+
  260. By default, numbers are encoded with 14 significant digits. Refer to
  261. <<encode_number_precision,+cjson.encode_number_precision+>> for details.
  262. Lua CJSON will escape the following characters within each UTF-8 string:
  263. - Control characters (ASCII 0 - 31)
  264. - Double quote (ASCII 34)
  265. - Forward slash (ASCII 47)
  266. - Blackslash (ASCII 92)
  267. - Delete (ASCII 127)
  268. All other bytes are passed transparently.
  269. [CAUTION]
  270. =========
  271. Lua CJSON will successfully encode/decode binary strings, but this is
  272. technically not supported by JSON and may not be compatible with other
  273. JSON libraries. To ensure the output is valid JSON, applications should
  274. ensure all Lua strings passed to +cjson.encode+ are UTF-8.
  275. Base64 is commonly used to encode binary data as the most efficient
  276. encoding under UTF-8 can only reduce the encoded size by a further
  277. &#126;8%. Lua Base64 routines can be found in the
  278. http://w3.impa.br/%7Ediego/software/luasocket/[LuaSocket] and
  279. http://www.tecgraf.puc-rio.br/%7Elhf/ftp/lua/#lbase64[lbase64] packages.
  280. =========
  281. Lua CJSON uses a heuristic to determine whether to encode a Lua table as
  282. a JSON array or an object. A Lua table with only positive integer keys
  283. of type +number+ will be encoded as a JSON array. All other tables will
  284. be encoded as a JSON object.
  285. Lua CJSON does not use metamethods when serialising tables.
  286. - +rawget+ is used to iterate over Lua arrays
  287. - +next+ is used to iterate over Lua objects
  288. Lua arrays with missing entries (_sparse arrays_) may optionally be
  289. encoded in several different ways. Refer to
  290. <<encode_sparse_array,+cjson.encode_sparse_array+>> for details.
  291. JSON object keys are always strings. Hence +cjson.encode+ only supports
  292. table keys which are type +number+ or +string+. All other types will
  293. generate an error.
  294. [NOTE]
  295. Standards compliant JSON must be encapsulated in either an object (+{}+)
  296. or an array (+[]+). If strictly standards compliant JSON is desired, a
  297. table must be passed to +cjson.encode+.
  298. By default, encoding the following Lua values will generate errors:
  299. - Numbers incompatible with the JSON specification (infinity, NaN)
  300. - Tables nested more than 1000 levels deep
  301. - Excessively sparse Lua arrays
  302. These defaults can be changed with:
  303. - <<encode_invalid_numbers,+cjson.encode_invalid_numbers+>>
  304. - <<encode_max_depth,+cjson.encode_max_depth+>>
  305. - <<encode_sparse_array,+cjson.encode_sparse_array+>>
  306. .Example: Encoding
  307. [source,lua]
  308. value = { true, { foo = "bar" } }
  309. json_text = cjson.encode(value)
  310. -- Returns: '[true,{"foo":"bar"}]'
  311. [[encode_invalid_numbers]]
  312. encode_invalid_numbers
  313. ~~~~~~~~~~~~~~~~~~~~~~
  314. [source,lua]
  315. ------------
  316. setting = cjson.encode_invalid_numbers([setting])
  317. -- "setting" must a boolean or "null". Default: false.
  318. ------------
  319. Lua CJSON may generate an error when encoding floating point numbers not
  320. supported by the JSON specification (_invalid numbers_):
  321. - infinity
  322. - NaN
  323. Available settings:
  324. +true+:: Allow _invalid numbers_ to be encoded using the Javascript
  325. compatible values +NaN+ and +Infinity+. This will generate
  326. non-standard JSON, but these values are supported by some libraries.
  327. +"null"+:: Encode _invalid numbers_ as a JSON +null+ value. This allows
  328. infinity and NaN to be encoded into valid JSON.
  329. +false+:: Throw an error when attempting to encode _invalid numbers_.
  330. This is the default setting.
  331. The current setting is always returned, and is only updated when an
  332. argument is provided.
  333. [[encode_keep_buffer]]
  334. encode_keep_buffer
  335. ~~~~~~~~~~~~~~~~~~
  336. [source,lua]
  337. ------------
  338. keep = cjson.encode_keep_buffer([keep])
  339. -- "keep" must be a boolean. Default: true.
  340. ------------
  341. Lua CJSON can reuse the JSON encoding buffer to improve performance.
  342. Available settings:
  343. +true+:: The buffer will grow to the largest size required and is not
  344. freed until the Lua CJSON module is garbage collected. This is the
  345. default setting.
  346. +false+:: Free the encode buffer after each call to +cjson.encode+.
  347. The current setting is always returned, and is only updated when an
  348. argument is provided.
  349. [[encode_max_depth]]
  350. encode_max_depth
  351. ~~~~~~~~~~~~~~~~
  352. [source,lua]
  353. ------------
  354. depth = cjson.encode_max_depth([depth])
  355. -- "depth" must be a positive integer. Default: 1000.
  356. ------------
  357. Once the maximum table depth has been exceeded Lua CJSON will generate
  358. an error. This prevents a deeply nested or recursive data structure from
  359. crashing the application.
  360. By default, Lua CJSON will generate an error when trying to encode data
  361. structures with more than 1000 nested tables.
  362. The current setting is always returned, and is only updated when an
  363. argument is provided.
  364. .Example: Recursive Lua table
  365. [source,lua]
  366. a = {}; a[1] = a
  367. [[encode_number_precision]]
  368. encode_number_precision
  369. ~~~~~~~~~~~~~~~~~~~~~~~
  370. [source,lua]
  371. ------------
  372. precision = cjson.encode_number_precision([precision])
  373. -- "precision" must be an integer between 1 and 14. Default: 14.
  374. ------------
  375. The amount of significant digits returned by Lua CJSON when encoding
  376. numbers can be changed to balance accuracy versus performance. For data
  377. structures containing many numbers, setting
  378. +cjson.encode_number_precision+ to a smaller integer, for example +3+,
  379. can improve encoding performance by up to 50%.
  380. By default, Lua CJSON will output 14 significant digits when converting
  381. a number to text.
  382. The current setting is always returned, and is only updated when an
  383. argument is provided.
  384. [[encode_sparse_array]]
  385. encode_sparse_array
  386. ~~~~~~~~~~~~~~~~~~~
  387. [source,lua]
  388. ------------
  389. convert, ratio, safe = cjson.encode_sparse_array([convert[, ratio[, safe]]])
  390. -- "convert" must be a boolean. Default: false.
  391. -- "ratio" must be a positive integer. Default: 2.
  392. -- "safe" must be a positive integer. Default: 10.
  393. ------------
  394. Lua CJSON classifies a Lua table into one of three kinds when encoding a
  395. JSON array. This is determined by the number of values missing from the
  396. Lua array as follows:
  397. Normal:: All values are available.
  398. Sparse:: At least 1 value is missing.
  399. Excessively sparse:: The number of values missing exceeds the configured
  400. ratio.
  401. Lua CJSON encodes sparse Lua arrays as JSON arrays using JSON +null+ for
  402. the missing entries.
  403. An array is excessively sparse when all the following conditions are
  404. met:
  405. - +ratio+ > +0+
  406. - _maximum_index_ > +safe+
  407. - _maximum_index_ > _item_count_ * +ratio+
  408. Lua CJSON will never consider an array to be _excessively sparse_ when
  409. +ratio+ = +0+. The +safe+ limit ensures that small Lua arrays are always
  410. encoded as sparse arrays.
  411. By default, attempting to encode an _excessively sparse_ array will
  412. generate an error. If +convert+ is set to +true+, _excessively sparse_
  413. arrays will be converted to a JSON object.
  414. The current settings are always returned. A particular setting is only
  415. changed when the argument is provided (non-++nil++).
  416. .Example: Encoding a sparse array
  417. [source,lua]
  418. cjson.encode({ [3] = "data" })
  419. -- Returns: '[null,null,"data"]'
  420. .Example: Enabling conversion to a JSON object
  421. [source,lua]
  422. cjson.encode_sparse_array(true)
  423. cjson.encode({ [1000] = "excessively sparse" })
  424. -- Returns: '{"1000":"excessively sparse"}'
  425. API (Variables)
  426. ---------------
  427. _NAME
  428. ~~~~~
  429. The name of the Lua CJSON module (+"cjson"+).
  430. _VERSION
  431. ~~~~~~~~
  432. The version number of the Lua CJSON module (+"2.1devel"+).
  433. null
  434. ~~~~
  435. Lua CJSON decodes JSON +null+ as a Lua +lightuserdata+ NULL pointer.
  436. +cjson.null+ is provided for comparison.
  437. [sect1]
  438. References
  439. ----------
  440. - http://tools.ietf.org/html/rfc4627[RFC 4627]
  441. - http://www.json.org/[JSON website]
  442. // vi:ft=asciidoc tw=72: