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