Documentation
Documentation
! Welcome to libjson 7. libjson is the fastest and more customizable json library for C and C++. It
has a special interface for C++, to allow C++ programmers to embed libjson within their program, and
because many of libjson’s functions are inlined, they will get a major optimization boost from the compiler.
! It also has a C-style interface for other programming languages and for sharing libraries. This
document will explain building and optimizing libjson to fit your needs, the C interface, and the C++
specialized interface. Each has their own part in this document.
! If you are upgrading from libJSON 5 or earlier, this new library has a different interface, so your
programs will break if you try and plug and play, but it should not be difficult to convert them, as all of the
functions are still there, they just have more standardized names.
! If you are upgrading from libjson 6, the only difference in the interface in json_validate.
! libjson’s interface will not change during minor or bug fix releases. Only major upgrades will (ie,
libjson 6 to libjson 7.)
! You should look at the changelog at the end of the document each time you upgrade, as things
may have been added or fixed that you are using.
About libjson
! libjson is a high speed complete JSON library, including parsers, writers, builders, formatters,
validators… It is also highly customizable. It may seem strange that libjson is considered a very
lightweight library, but the documentation is 200 pages long and there are dozens of source files, but the
fact is that very little of the library gets complied at any given time. The JSONOptions.h file sets options
for which parts are compiled and how they are. This document will tell you if function behave differently
or are unavailable under certain options.
! libjson was written with performance in mind. It is fast, and uses very little memory. Low level
memory manipulation allows libjson to do some speed tricks that less fine-tuned libraries don’t do. The
loads of preprocessor options means that there are few conditions at run-time, allowing it to focus as
much energy on the task at hand. The options allow you to optimize libjson for your program. See the
Optimizing libjson section near the end of this document.
! I also gave it more customizability than any other library, including mutex managers, garbage
collection, memory control, and unicode support, all optional of course, and not on by default. There is a
clean C interface, with all methods using C - style names and all prefixed with json_. There is also a very
intuitive C++ interface complete with iterators, and a very STL - style interface. These two libraries share
some code, but also have version specific code.
! libjson is also quiet secure, it is immune from most DoS attacks with it’s default options on and its
security options are all configurable.
If you email from your sourceforge account, be sure that you’re able to receive replies. It seems that the
default behavior of sourceforge turns this off, I’ve gotten lots of requests for help that I’ve been unable to
respond to, I try my best to find another way to answer you, but I can’t always.
Supported platforms! 8
Building libjson! 9
JSONOptions.h! 9
JSON_LIBRARY! 10
JSON_STRICT! 11
JSON_DEBUG! 12
JSON_ISO_STRICT! 13
JSON_SAFE! 14
JSON_CASTABLE! 15
JSON_STDERROR! 16
JSON_PREPARSE! 17
JSON_LESS_MEMORY! 18
JSON_UNICODE! 19
JSON_REF_COUNT! 20
JSON_BINARY! 21
JSON_EXPOSE_BASE64! 22
JSON_ITERATORS! 23
JSON_STREAM! 24
JSON_MEMORY_CALLBACKS! 25
JSON_MEMORY_MANAGE! 26
JSON_MEMORY_POOL! 27
JSON_MUTEX_CALLBACKS! 28
JSON_MUTEX_MANAGE! 29
JSON_NO_C_CONSTS! 30
JSON_OCTAL! 31
JSON_READ_PRIORITY! 32
JSON_WRITE_PRIORITY! 33
JSON_NEWLINE! 34
JSON_INDENT! 35
JSON_ESCAPE_WRITES! 36
JSON_COMMENTS! 37
JSON_WRITE_BASH_COMMENTS! 38
JSON_WRITE_SINGLE_LINE_COMMENTS! 39
ARRAY_SIZE_ON_ONE_LINE! 40
JSON_VALIDATE! 41
JSON_CASE_INSENSITIVE_FUNCTIONS! 42
JSON_INDEX_TYPE! 43
JSON_BOOL_TYPE! 44
JSON_INT_TYPE! 45
JSON_NUMBER_TYPE! 46
JSON_STRING_HEADER! 47
JSON_NO_EXCEPTIONS! 48
JSON_DEPRECATED_FUNCTIONS! 49
JSON_SECURITY_MAX_NEST_LEVEL! 50
JSON_SECURITY_MAX_STRING_LENGTH! 51
JSON_SECURITY_MAX_STREAM_OBJECTS! 52
JSON_UNIT_TEST! 53
Testing libjson! 54
Benchmarking! 54
C interface ! 55
JSONNODE types! 55
libjson types! 55
JSONNODE functions! 57
Inspector functions! 57
Modifier Functions! 58
Streaming Functions! 58
json_new! 61
json_new_a! 62
json_new_i! 63
json_new_f! 64
json_new_b! 65
json_copy! 66
json_duplicate! 67
json_delete! 68
json_delete_all! 69
json_new_stream! 70
json_stream_push! 71
json_stream_reset! 72
json_type! 73
json_size! 74
json_empty! 75
json_name! 76
json_get_comment! 77
json_as_string! 78
json_as_int! 79
json_as_float! 80
json_as_bool! 81
json_as_node! 82
json_as_array! 83
json_as_binary! 84
json_write! 85
json_write_formatted! 86
json_equal! 87
json_set_a! 88
json_set_i! 89
json_set_f! 90
json_set_b! 91
json_set_n! 92
json_set_name! 93
json_set_comment! 94
json_clear! 95
json_swap! 96
json_merge! 97
json_preparse! 98
json_set_binary! 99
json_cast! 100
json_at! 101
json_get! 102
json_get_nocase! 103
json_reserve! 104
json_push_back! 105
json_pop_back_at! 106
json_pop_back! 107
json_pop_back_nocase! 108
json_find! 109
json_find_nocase! 110
json_erase! 111
json_erase_multi! 112
json_insert! 113
json_insert_multi! 114
json_begin! 115
json_end! 116
json_lock! 117
json_unlock! 118
json_set_mutex! 119
json_set_global_mutex! 120
json_parse! 121
json_parse_unformatted! 122
json_strip_white_space! 123
json_is_valid! 124
json_is_valid_unformatted! 125
json_register_debug_callback! 127
json_register_mutex_callbacks! 128
json_register_memory_callbacks! 129
json_free! 130
json_free_all! 131
json_encode64! 132
json_decode64! 133
JSON_TEXT! 134
JSONNode::JSONNode! 141
JSONNode::~JSONNode! 143
JSONNode::duplicate! 144
JSONNode::operator =! 145
JSONNode::type! 149
JSONNode::size! 150
JSONNode::empty! 151
JSONNode::name! 152
JSONNode::get_comment! 153
JSONNode::as_string! 154
JSONNode::as_int! 155
JSONNode::as_float! 156
JSONNode::as_bool! 157
JSONNode::as_node! 158
JSONNode::as_array! 159
JSONNode::as_binary! 160
JSONNode::dump! 161
JSONNode::write! 162
JSONNode::write_formatted! 163
JSONNode::set_name! 164
JSONNode::set_comment! 165
JSONNode::clear! 166
JSONNode::swap! 167
JSONNode::merge! 168
JSONNode::preparse! 169
JSONNode::set_binary! 170
JSONNode::cast! 171
JSONNode::at! 172
JSONNode::at_nocase! 173
JSONNode::reserve! 175
JSONNode::push_back! 176
JSONNode::pop_back! 177
JSONNode::pop_back_nocase! 178
JSONNode::find! 179
JSONNode::find_nocase! 180
JSONNode::erase! 181
JSONNode::insert! 182
JSONNode::begin! 184
JSONNode::end! 185
JSONNode::rbegin! 186
JSONNode::rend! 187
JSONNode::set_mutex! 188
JSONNode::lock! 189
JSONNode::unlock! 190
JSONStream ! 191
JSONStream::JSONStream! 192
JSONStream::~JSONStream! 193
JSONStream::operator =! 194
JSONStream::reset! 196
libjson! 197
libjson::parse! 199
libjson::parse_unformatted! 200
libjson::strip_white_space! 201
libjson::is_valid! 202
libjson::is_valid_unformatted! 203
libjson::register_debug_callback! 205
libjson::register_mutex_callbacks! 206
libjson::set_global_mutex! 207
libjson::register_memory_callbacks! 208
libjson::encode64! 209
libjson::decode64! 210
libjson::to_std_string! 211
libjson::to_std_wstring! 212
libjson::to_json_string! 213
JSON_TEXT! 214
Roadmap! 218
Changelog! 219
License! 225
Supported platforms
! libjson officially supports and has been tested on the following platforms
! More compilers are being added as I get word that it is working on them. If you are using a
different compiler than one on this list, it should would. The code is meant to be platform and compiler
independent. If there are minor incompatibilities, please open a ticket on sourceforge and I will get it fixed
as soon as I can.
Building libjson
! libjson is designed for customizability by experts, but also ease of use by novices. Most users
simply need to make the library. If you are planning on embedding it in your C++ program, then all you
have to do is add libjson’s source to your project and comment JSON_LIBRARY in JSONOptions.h.
libjson does not use anything other than built-in C++ and any compiler should compile it.
JSONOptions.h
! In the source code you will find a file called JSONOptions.h, which is used for configuring libjson’s
build. All of the options are in there and it’s recommended that you leave them, just comment out what
you don’t need. There is a brief description of each option in the file, as well as a more extensive
explanation further down in this document.
! I chose to use a file for the options in libjson instead of forcing the user to know compile options
and change them in the project and make files. I think this is easier.
! It is recommended that you build and run the Unit Test before compiling for the library or using it
in C++. As there are billions of combinations of options, not all of them have been tested together. If the
build failed, please take out a ticket on sourceforge: http://sourceforge.net/tracker/?group_id=314112 or
email the author at [email protected]. Your issue will be quickly fixed and your options added to the
quarter of a million unit tests that are already run, that way regression of the bug is impossible.
Make Options
! Thanks to Bernhard Fluehmann, libjson now has a proper makefile. The options of how libjson
behaves are all in JSONOptions, but the way it compiles depends on the options you give the make file.
The most common options for the makefile are BUILD_TYPE, SHARED, and install.
! Running make by itself will cause the library to be built as a static library, exactly where the
source is. Doing make install will install it in the exec_prefix. By default, exec_prefix is /usr/local, but you
can set this as an option too.
! To build libjson for specific purposes, you can set the BUILD_TYPE parameter. This is set to the
same values as libjson 6’s target: small or debug;
BUILD_TYPE=debug BUILD_TYPE=small
! libjson now also has an option to compile as a shared or static library. Shared libraries are quite
useful if you have multiple programs that all require json functionality. To use a shared library make
SHARED=1. By default, SHARED is 0, so it will output a static library. The extension for a shared library
is hard coded as .so in the makefile. To use .dll or .dylib, you will have to edit the make file. There are a
few more options, all documented in the makefile itself.
JSON_LIBRARY
! This option exposes only the C-style interface, which is used for static and dynamic library
compilation so that it can be shared by multiple programs, or used by non-C++ programming languages.
This C interface is a little simpler so that it is compatible with most programming languages primitives, but
the overall functionality remains the same.
Recommended for
! Sharing the library among multiple programs, dynamically loading the library, or using it in a
programming language other than C++.
On by default
! Yes
JSON_STRICT
! This option makes libjson strictly adhere to the specs laid out for JSON. This eliminates all
support for comments, hexadecimal and octal values, and various other things that libjson supports that
isn’t standard.
Recommended for
! Programmers who want a bare-bones strict JSON library and nothing more.
Requirements
On by default
! No
JSON_DEBUG
! This option is used to create a debugging version of the library. It does a lot of checks not only of
the json, but also of the library itself. This is recommended only while writing your software, but not for
release, as it is a little bit slower.
! This option exposes libjson::registerDebugCallback in C++ and json_register_debug_callback in
C, which allows you to get feedback from libjson if something goes wrong. This will not protect against
errors, only let you know about them before it crashes. If you want to catch errors and handle them
gracefully, then turn on JSON_SAFE as well. You can also turn on JSON_STDERROR, which hides the
callbacks and prints problems to stderr.
! This option also exposes the JSONNode::dump function in C++, which allows you inspect the
internal workings of libjson, which can be useful for debugging. I chose to omit this from the C interface
because it is mostly used by the author and maintainers.
Recommended for
On by default
! No
JSON_ISO_STRICT
! This option makes libjson use iso strict settings. This includes doing things like removing any
non-standard C++ functionality like long longs and wchar_t.
Recommended for
On by default
! Depends, usually it is off, but if you compile on GCC with -ansi, this option will turn itself on and
warn you that you left it off
JSON_SAFE
! This option is also used for debugging, but can also be useful if you think that your program might
receive json that is not properly formatted. If libjson encounters something it it considers an error, then it
will tell you through the callback or stderr, depending on the other options. then handle it gracefully. This
option is required for validation.
Recommended for
! Programs that might receive incorrect json, or if you need to validate json. If your sure that your
json will be correct, then there is no need for this option.
On by default
! Yes
JSON_CASTABLE
! This option creates implicit casts between internal types. For example, if you call as_int on a
bool, with this option turned on, it will return 1 if true, and 0 if false. If this option is not on, this behavior is
undefined. This makes libjson more flexible, but also makes the binary larger.
Recommended for
On by default
! Yes
JSON_STDERROR
! This option is will route all error messages to cerr instead of the callback. It hides
libjson::registerDebugCallback and json_register_debug_callback as they are not needed. You can see
the errors in the console.
Recommended for
! Debugging for those who do not want to handle error messages in a special way.
On by default
! No
JSON_PREPARSE
! This option forces libjson to parse the entire json string at once. By default, libjson does on-the-
fly parsing for speed reasons. This makes initial parsing much faster and use much less memory, but
subsequent reads of it slightly slower. This options switches those.
Recommended for
! Programs that use all or most of the json that it receives. Because json is largely used for
communication from client to server, often the server will send more information that needed, so parsing
all of it wastes time for no reason. However, json can also be used for configuration files as well as other
things, so in cases like that, it might be preferable to use this option.
On by default
! No
JSON_LESS_MEMORY
! This option makes libjson use about 20% less memory on average. When libjson is done using
memory, it doesn’t always release all of it, it keeps it allocated so that any future requests to push memory
back is much faster. This option doesn't allow that to happen, it instantly releases all extra memory.
! This also turns off hot spot optimizations under GCC, but turns on the better packing.
Recommended for
! Programs that need as much memory as possible. Possibly for embedded programming, or
programs that might end up using billions of nodes and need as much memory as possible.
On by default
! No
JSON_UNICODE
! This option makes libjson use wide strings both internally and for the interface. Because the
JSON standard specifies that it must support full UTF8, libjson can not meet this standard without wide
characters. However, because these multi-byte characters are rarely used, this is optional, and off by
default.
Recommended for
Requirements
On by default
! No
JSON_REF_COUNT
! This option makes libjson’s nodes reference count and copy-on-write it’s internal structure. This
makes passing by value and copying nodes very fast, but less thread-safe.
Recommended for
! Programmers that want to copy and pass by value often. Also by programmers who take
JSONNodes just to read them. It is recommended if you are interacting with your json with multiple
threads, that you turn this option off, or use the JSON_MUTEX_CALLBACKs options and use critical
sections.
On by default
! Yes
JSON_BINARY
! This option turns on the set_binary and get_binary functions. Because the JSON standard offers
no way to encode true binary data, libjson (like most json libraries) uses Base64 to encode and decode
binary data into text. This allows you to transport binary data between server and client, such as images
or files. If you already have a base64 library, then you don’t need this, however, this one is highly
optimized and will probably be faster than most others.
Recommended for
! Programs that have to encode and decode binary data such as images. It can also be used to
obfuscate data.
On by default
! Yes
JSON_EXPOSE_BASE64
! This option exposes an interface to libjson’s base64 encoding functions. Normally, these are
hidden behind the scenes (and off unless JSON_BINARY is turned on,) but sometimes you may want a
high-speed base64 encoder to accompany libjson. It is inefficient to have a base64 encoder/decoder
AND libjson in your project. libjson’s encoder and decoder is by far the fastest I’ve come across, and
already therefor you. JSON is often used in networking, and base64 is often also required in networking.
Recommended for
! Programs that have to encode and decode binary data such as images. It can also be used to
obfuscate data.
On by default
! Yes
JSON_ITERATORS
! This option turns on iterator functions for libjson. erase, find, insert are exposed when this option
is on. In C++ mode you’ll find iterator functions to be very STL-like, and there is even support for iterators
in the library, but more restrictive.
Recommended for
! Programmers familiar and comfortable with STL iterators or need advanced manipulation
methods.
On by default
! Yes
JSON_STREAM
! This option turns on streaming functions for libjson. This allows you buffer json, and send it to the
stream a little bit at a time.
Recommended for
! Programs that want to buffer json, or need to stream from the internet.
On by default
! Yes
JSON_MEMORY_CALLBACKS
! This option exposes functions to register callbacks for allocating, resizing, and freeing memory.
Because libjson is designed for speed, it is feasible that some users would like to further add speed by
having the library utilize a memory pool. With this option turned on, the default behavior is still done
internally unless a callback is registered
Recommended for
! Programs that want to use custom memory handling functionality, such as memory pools and
garbage collection.
On by default
! No
JSON_MEMORY_MANAGE
! This option exposes functions to bulk delete all memory that libjson has allocated for you. This
includes strings and nodes. Usually, you are required to keep track of all of the nodes and strings that
libjson creates, but with this option you don’t have to.
Recommended for
! Programs that use lots of strings and nodes and want to de bulk cleanups or memory managers.
On by default
! No
JSON_MEMORY_POOL
! This option turns on memory pooling within libjson. This is more efficient usually that just
attaching the callbacks to a memory pool because it creates a few of them internally, which are optimized
for specific tasks.
! JSON is often used for server and/or client communication. This often entails parsing json, then
creating json, then ending the session. It doesn’t make sense to allocate and deallocate memory over
and over again, so the memory pool allocates lots of space for this all at once.
Recommended for
On by default
! No
JSON_MUTEX_CALLBACKS
! This option exposes functions to register callbacks to lock and unlock mutexs and functions to
lock and unlock JSONNodes and all of it's children. This does not prevent other threads from accessing
the node, but will prevent them from locking it. Because of libjson’s extremely complex internal working
and reference counting, it is much easier for the end programmer to allow libjson to manage your mutexs
because of reference counting and manipulating trees, libjson automatically tracks mutex controls for you,
so you only ever lock what you need to.
Recommended for
On by default
! No
JSON_MUTEX_MANAGE
! This option lets you set mutexes and forget them, libjson will not only keep track of the mutex, but
also keep a count of how many nodes are using it, and delete it when there are no more references. This
changes the registerMutexCallbacks and json_register_mutex_callbacks to require a third deleter
callback as well.
Recommended for
! Programs that require libjson be used in critical sections and handle it’s own mutexes.
Requirements
On by default
! No
JSON_NO_C_CONSTS
! This option removes the const qualifier for the function declarations. The functions do not behave
any differently, they simply have a slightly different interface.
Recommended for
On by default
! No
JSON_OCTAL
! This option turns on features for supporting octal values in strings and numbers. Normally, octal
numbers are treated as decimal
Recommended for
On by default
! No
JSON_READ_PRIORITY
! This option exposes libjson’s parsing functionality, and sets it’s priority. By default reading is high
priority, but if the majority of your time is spent writing, you can lower the priority to produce a better
writing engine.
Recommended for
On by default
! Yes (HIGH)
JSON_WRITE_PRIORITY
! This option exposes the write and write_formatted functionality. Without this option, libjson is
read-only, this allows you to write json as well. This also sets the priority of the writing, some compilers
will generate different code depending on the priority that you give.
Recommended for
! Programs that need to write json, such as two way communication or recording a config file after
it has changed.
On by default
! Yes (MED)
JSON_NEWLINE
! This option is used for writing formatted json using specialized newlines. By default, libjson will
use the UNIX newline character. Simply defining this option is not adequate, you must define it to
something. Whatever it’s defined to will be used. The JSONOptions.h file included with libjson shows
you how, as it defined is as a carriage return followed by a newline character, this is standard on Windows
or MS-DOS. You may also want to set it to </br> (the new line tag for HTML.)
! Even if you are using unicode, write the value of the newline in regular quotes, libjson will
automatically make ii unicode for you (in preprocessor.)
Recommended for
! Programs that write formatted JSON that require special newline characters.
On by default
! No
JSON_INDENT
! This option is used for writing formatted json using specialized indents. By default, libjson will use
the ASCII tab character. Simply defining this option is not adequate, you must define it to something.
Whatever it’s defined to will be used. The JSONOptions.h file included with libjson shows you how, you
will most commonly change it to spaces, but HTML might also be common.
! Even if you are using unicode, write the value of the newline in regular quotes, libjson will
automatically make ii unicode for you (in preprocessor.)
Recommended for
! Programs that write formatted JSON that spaces to indent instead of tabs.
On by default
! No
JSON_ESCAPE_WRITES
! This option is used for writing json where the special characters have been escaped. This is on
by default, because without it, the json no longer meets the standards. If it’s off special characters like
newlines, tabs, and special unicode characters are simply place in the json as they appear. This may
cause problems with other JSON engines, and it will not pass validation, so it is recommended that you
leave it on.
Recommended for
! Programs that write JSON and want to adhere to the JSON standard, or communicate between
other json engines.
On by default
! Yes
JSON_COMMENTS
! This option tells libjson to store and write comments. libjson always supports parsing json that
has comments in it as it simply ignores them, but with this option it keeps the comments and allows you to
insert further comments.
! libjson will automatically determine if comments are multiline or single line and write them
accordingly.
Recommended for
! Programs that write complex JSON that might be read by human eyes. Comments make JSON
easier to understand and alter.
On by default
! Yes
JSON_WRITE_BASH_COMMENTS
! This option tells libjson to use bash comments to output json with comments. Bash comments
are the # character. This also disables multi-line comments in the C-style (/* */). Instead it will simply put
multiple lines, all with leading # characters.
Recommended for
On by default
! No
JSON_WRITE_SINGLE_LINE_COMMENTS
! This option tells libjson to not use the C-style multi-line comment, as some JSON libraries don’t
support them. This will write multi-line comments as a series of // comments instead.
Recommended for
! Programs that need to output JSON that libraries that don’t support multiline comments need to
read.
On by default
! No
ARRAY_SIZE_ON_ONE_LINE
! This option allows libjson to write small arrays all on one line. This is commonly done to make
things easier to read, specifically for things like coordinates. This will only affect writing of primitives,
objects and arrays are done as normal. You have to set this to an integer, where anything smaller or
equal to the value is treated specially.
Recommended for
On by default
! No
JSON_VALIDATE
! This option exposes validation functions. For programs that might get invalid json, validation
might be required before anything is done.
Recommended for
Requirements
On by default
! Yes
JSON_CASE_INSENSITIVE_FUNCTIONS
! This option exposes case-insensitive functions. This includes at, get, find...
Recommended for
On by default
! Yes
JSON_INDEX_TYPE
! This option changes the type that is used to track the number of children. Usually unsigned int is
used because it’s fast and efficient, but there are cases where it’s not desired. For instance, on
embedded systems where there is little memory, one might choose to use a short or even a char. Or on
huge 64-bit systems where the number of nodes may go outside the range of an unsigned int.
Recommended for
On by default
! No
JSON_BOOL_TYPE
! This option changes the bool type in the C interface. This allows you to change the interface to fit
the language that you are working with. If this option is not on, then the bool type is an int, but you can
make it anything.
Recommended for
On by default
! No
JSON_INT_TYPE
! This option changes the int type for as_int. If this option is not on, then int type is a long
Recommended for
! People who want to get different types out of the as_int function, possible for high precision.
On by default
! No
JSON_NUMBER_TYPE
! This option changes the number type for as_float. If this option is not on, then number type is a
double in most cases, but in JSON_LESS_MEMORY mode, it squeezes into a float.
Recommended for
! People who need extra control, or may want a long double for more precision.
On by default
! No
JSON_STRING_HEADER
! This option changes the string type that libjson uses for both it’s interface and internals. This can
be very useful for working with other libraries. For instance, developers using Qt or wxWigdets. Both are
very common and have their own string class. Both should be able to be dropped right in without much
problem. The class must be named or typedefed json_string.
! If you change this option and are using the C++ interface, then you must recompile the entire
library because this makes a dynamic dependency that your IDE or compiler will not pick up on.
Recommended for
On by default
! No
JSON_NO_EXCEPTIONS
! This option shuts off all exceptions at the interface level. For the functions that throw exceptions,
their differences are documented in the method documentation.
Recommended for
On by default
! No
Note
! If you use the JSON_PREPARSE option, exceptions are used internally, other than that,
exceptions are completely removed from the library.
JSON_DEPRECATED_FUNCTIONS
! This option leaves functions that are not supposed to be used anymore. You will get compiler
warnings if you try to use these functions, but they will behave just as they did before they were
deprecated.
Recommended for
On by default
! Yes
JSON_SECURITY_MAX_NEST_LEVEL
! This option is used to prevent DoS (denial of service) attacks. Hackers sometimes try to use
deeply nested JSON to make a server hang, this security option stops libjson from going too deeply. It
must be defined as an integer. The security checks are done during validation, not parsing.
Recommended for
On by default
! Yes (128)
JSON_SECURITY_MAX_STRING_LENGTH
! This option is used to prevent DoS (denial of service) attacks. Hackers sometimes try to use very
long JSON strings to make a server hang, this security option stops libjson from even trying to parse a
string that is too large. It must be defined as an integer. The security checks are done during validation,
not parsing.
Recommended for
On by default
! This option is used to prevent DoS (denial of service) attacks. Hackers sometimes try to use very
long JSON strings of lots of small objects to make a server hang, this security option stops libjson from
even trying to parse a string that is too large. It must be defined as an integer.
Recommended for
On by default
! Yes (128)
JSON_UNIT_TEST
! This option is used to maintain and debug the libjson. It makes all private members and functions
public so that tests can do checks of the inner workings of libjson. This should not be turned on by end
users.
Recommended for
On by default
! No
Testing libjson
! libjson should work with any combination of options (excluding illegal ones of course,) but
because of the number of options, and platforms, it is not possible to test them all. That is why libjson
includes a test suite.
! Once you have all of the options set the way that you want them, it is time to test libjson. Unzip
the TestSuite zip, and navigate to it in the console.
Benchmarking
! libjson also comes with a benchmark setup. Navigate to TestSuite/Benchmark and do as you did
before.
! This will run 5 loops, which ill allow you to compare speed with different options set. This is
useful if you find libjson acting as a bottleneck for some reason. Depending on the speed of your
computer, this may take a few minutes.
C interface
! libjson has an interface that uses standard C types and a standard C interface. This interface
doesn’t have to be used in just C, it can be used in Basic, C, C++ and any other language that supports
the C interface (most do.) All methods in libjson begin with “json_” to make sure that the names don’t
collide with other libraries or any of your methods.
JSONNODE types
Function Description
JSON_STRING A string
libjson types
Function Description
Function Description
Inspector functions
Function Description
Function Description
Streaming Functions
Function Description
Function Description
Iterator Functions
Function Description
Function Description
Function Description
Callback Registration
Function Description
Cleanup Functions
Function Description
Base64 Functions
Function Description
Text Functions
Function Description
New Node
! This function creates an empty node of the specified type. This would normally be used to start
serializing something or writing a configuration file. You must json_delete the resulting node or attach it to
something as a child.
Option Differences
Parameters
mytype
The enumerated type of the JSONNODE.
Return Value
Empty node
Complexity
Constant
json_new_a
New Node
! This function creates a string node with the name and value specified. You must json_delete the
resulting node or attach it to something as a child.
Option Differences
Parameters
name
The node’s name, this may be NULL
value
The node’s value, this should not be NULL
Return Value
A new node
Complexity
Constant
json_new_i
New Node
! This function creates a integer node with the name and value specified. You must json_delete
the resulting node or attach it to something as a child.
Option Differences
Parameters
name
The node’s name, may be NULL
value
The node’s value
Return Value
A new node
Complexity
Constant
json_new_f
New Node
! This function creates a floating point node with the name and value specified. You must
json_delete the resulting node or attach it to something as a child.
Option Differences
Parameters
name
The node’s name, may be NULL
value
The node’s value
Return Value
A new node
Complexity
Constant
json_new_b
New Node
! This function creates a boolean node with the name and value specified. You must json_delete
the resulting node or attach it to something as a child.
! It’s important to note that this function takes an int as the value, Some languages do not have a
bool type (including C89.)
Option Differences
Parameters
name
The node’s name, may be NULL
value
The node’s value
Return Value
A new node
Complexity
Constant
json_copy
Copy Node
! This function copies a JSONNODE and returns the new copy. With reference counting, this
operation is extremely fast. If you want a literal copy and not a reference count, use json_duplicate.
Option Differences
Parameters
node
The node to be copied
Return Value
Complexity
Constant, unless JSON_REF_COUNT is on, in which case it’s the same as json_duplicate.
json_duplicate
Duplicating JSONNODE
Constructs a JSONNODE object, by copying the contents of JSONNODE. This is different from the
json_copy because it makes a literal copy, not reference counting.
Option Differences
None
Parameters
node
The node to be copied
Return Value
Complexity
Linear on json_size, however, because JSON is a tree structure it's worse case scenario is linear on
json_size + json_size of each child recursively.
json_delete
Destruct JSONNODE
Option Differences
None
Parameters
node
The node to be deleted
Return Value
None
Complexity
! Depends on circumstances. If it's reference count is not one, then it's complexity is constant, if
it's the sole owner of it's value, then it becomes linear on JSONNode::size, however, because JSON is a
tree structure it's worse case scenario is linear on JSONNode::size + JSONNode::size of each child
recursively.
json_delete_all
void json_delete_all(void);
! Deletes all nodes that have been allocated by libjson. This is for bulk delete when you are done
with libjson for the time.
Option Differences
Parameters
None
Return Value
None
Complexity
New Stream
! This function creates a stream. Streams are used for pushing small amounts of json at a time, it
may be incomplete json, or even multiple json nodes, and the callback you give it will be called whenever
a complete node is recognized.
! Your callback must assume that the node given to it will be immediately deleted once the callback
is finished, so if you need to keep it, you must copy it.
Option Differences
Parameters
callback
The method that gets called whenever nodes are completed
e_callback
The method that gets called whenever the stream encounters bad json
id
The pointer that will get passed back into the callback method JSONSTREAM_SELF is
recommended, as it will tell the callback to use itself as the pointer
Return Value
A new stream
Complexity
Constant
json_stream_push
Push to stream
Pushes more text to the stream. If the stream sees that you have completed a node, it will call the
callback.
Option Differences
Parameters
stream
! The stream to push onto
text
! The text to add to the stream
Return Value
None
Complexity
Constant
json_stream_reset
Resets a stream
Option Differences
Parameters
stream
! The stream to reset
Return Value
None
Complexity
Constant
json_type
Return type
Option Differences
None
Parameters
none
Return Value
Complexity
Constant
json_size
Return size
Returns the number of children that the node has. This should be zero for anything other than
JSON_ARRAY or JSON_NODE, but this is only guaranteed with the JSON_SAFE option turned on. This
is because casting may or may not purge the children.
Option Differences
JSON_SAFE - will guarantee that anything other than JSON_NODE and JSON_ARRAY will return 0.
Parameters
None
Return Value
Complexity
Constant.
json_empty
Return empty
Returns whether or not the node has any children. If the node is not of JSON_NODE or JSON_ARRAY it
will invariably return true. Note that it returns an int, because some languages do not have a bool type.
Option Differences
None
Parameters
node
The node to perform this function on
Return Value
Complexity
Constant.
json_name
Return name
Returns the name of the node. If there is no name, then it returns a blank string.
Option Differences
None
Parameters
node
The node to perform this function on
Return Value
Complexity
Constant.
json_get_comment
Return comment
Option Differences
Parameters
node
The node to perform this function on
Return Value
Complexity
Constant.
json_as_string
Returns the string representation of the node. This may be different depending on the type of the node
Function Description
JSON_ARRAY “”
JSON_NODE “”
Notice that both JSON_NODE and JSON_ARRAY return empty strings. Use json_write and
json_write_formatted to output JSON.
Option Differences
JSON_CASTABLE - if this option is turned on, all return values are undefined except for JSON_STRING
Parameters
node
The node to perform this function on
Return Value
Complexity
Constant.
json_as_int
Returns the integer representation of the node. This may be different depending on the type of the node
Function Description
JSON_NULL 0
JSON_ARRAY Undefined
JSON_NODE Undefined
If the value is actually a floating point value, then libjson will record an error via it's callback, but will
continue on ahead and simply truncate the value. So 15.9 will be returned as 15. If JSON_DEBUG is
turned on, it will also error if the value of the node is outside the range of the long long datatype.
Option Differences
JSON_CASTABLE - if this option is turned on, all return values are undefined except for JSON_NUMBER
Parameters
node
The node to perform this function on
Return Value
Complexity
Constant.
json_as_float
Returns the floating point representation of the node. This may be different depending on the type of the
node
Function Description
JSON_NULL 0.0
JSON_STRING atof(as_string)
JSON_NUMBER Value
JSON_ARRAY Undefined
JSON_NODE Undefined
Option Differences
JSON_CASTABLE - if this option is turned on, all return values are undefined except for JSON_NUMBER
Parameters
node
The node to perform this function on
Return Value
Complexity
Constant.
json_as_bool
Returns the boolean representation of the node. This may be different depending on the type of the node
Function Description
JSON_NULL FALSE
JSON_STRING Undefined
JSON_BOOL Value
JSON_ARRAY Undefined
JSON_NODE Undefined
Option Differences
JSON_CASTABLE - if this option is turned on, all return values are undefined except for JSON_BOOL
Parameters
node
The node to perform this function on
Return Value
Complexity
Constant.
json_as_node
Returns the node representation of the node. For anything other than node and array, it simply returns an
empty node. If the caller is an array, it will convert it to a node.
Function Description
This command creates a new JSONNODE that has to be deleted or attached to a parent.
Option Differences
None
Parameters
node
The node to perform this function on
Return Value
Complexity
Constant for all except JSON_ARRAYs and JSON_NODEs which are the same as the json_copy
function.
json_as_array
Returns the array representation of the node. For anything other than node and array, it simply returns an
empty array. If the caller is an node, it will convert it to an array by stripping all of the names of each
child.
Function Description
This command creates a new JSONNODE that has to be deleted or attached to a parent.
Option Differences
None
Parameters
node
The node to perform this function on
Return Value
Complexity
Constant for anything other than a node. For a JSON_NODE, it is linear with respect to json_size, and
JSON_ARRAY which is the same as the json_copy function.
json_as_binary
Returns the binary value that was part of this node. It returns a byte array which is the original binary
data. It gives you how large the array is by the pass by pointer size parameter.
Function Description
JSON_NULL Undefined
JSON_NUMBER Undefined
JSON_BOOL Undefined
JSON_ARRAY Undefined
JSON_NODE Undefined
Option Differences
JSON_BINARY - If this option is not on, then this function is not accessible.
Parameters
node
The node to perform this function on
size
A pointer to an unsigned long, which will tell you how many bytes the data is
Return Value
Complexity
Write JSON
Returns JSON text, with no white space or comments. Designed to create JSON that is very small, and
therefore, faster to send between servers or write to a disk. The flipside is that it’s nearly impossible to
read by human eyes.
Only root nodes (JSON_NODE and JSON_ARRAYs) are meant to be written, all others will return a blank
string.
Option Differences
JSON_WRITER - If this option is not on, then this function is not accessible.
JSON_ESCAPE_WRITES - Escapes special characters
Parameters
node
The node to perform this function on
Return Value
Complexity
Linear with respect to the size of the tree underneath the node.
json_write_formatted
Write JSON
Returns JSON text that has been indented and prettied up so that it can be easily read and modified by
humans.
Only root nodes (JSON_NODE and JSON_ARRAYs) are meant to be written, all others will return a blank
string.
Option Differences
JSON_WRITER - If this option is not on, then this function is not accessible.
JSON_COMMENTS - If this option is not turned on, the no comments are written
JSON_WRITE_BASH_COMMENTS - This option will make libjson write only bash style # comments
JSON_WRITE_SINGLE_LINE_COMMENTS - This option will make libjson not write C-style /* */
comments
JSON_ESCAPE_WRITES - Escapes special characters
Parameters
node
The node to perform this function on
Return Value
Complexity
Linear with respect to the size of the tree underneath the node.
json_equal
Comparing JSONNODE
! Checks if the value held within the nodes are equal. This ignores things like comments, but for
JSON_NODE and JSON_ARRAYs, this is a deep comparison, checking each child too.
Option Differences
None
Parameters
node1
! The value to compare to
node2
! Another node to compare to
Complexity
! Constant except for JSON_NODEs and JSON_ARRAYs in which case it’s linear with respect to
size() and size() of each child recursively.
json_set_a
Option Differences
Parameters
node
The node to perform this function on
value
The new value of the node, shouldn’t be NULL unless JSON_SAFE is on
Return Value
None
Complexity
Constant
json_set_i
Option Differences
none
Parameters
node
The node to perform this function on
value
The new value of the node
Return Value
None
Complexity
Constant
json_set_f
Option Differences
None
Parameters
node
The node to perform this function on
value
The new value of the node
Return Value
None
Complexity
Constant
json_set_b
Sets the boolean value of the JSONNODE. The value is an int because of the missing bool datatype in
C.
Option Differences
None
Parameters
node
The node to perform this function on
value
The new value of the node
Return Value
None
Complexity
Constant
json_set_n
Sets the value of the JSONNODE to the value of the other, usually through fast and simple reference
counting.
Option Differences
None
Parameters
node
The node to perform this function on
value
The new value of the node
Return Value
None
Complexity
Constant
json_set_name
Option Differences
Parameters
node
The node to perform this function on
name_t
The name of the node
Return Value
None
Complexity
Constant
json_set_comment
Option Differences
Parameters
node
The node to perform this function on
comment_t
The comment attached to the node
Return Value
None
Complexity
Constant
json_clear
Clearing a node
Option Differences
None
Parameters
node
The node to perform this function on
Return Value
None
Complexity
Swaps the contents of two nodes. This is very fast because JSONNODE is just a wrapper around an
internal structure, so it simply swaps pointers to those structures.
Option Differences
None
Parameters
node1
The node to perform this function on
node2
The node to swap values with
Return Value
None
Complexity
Constant
json_merge
It’s possible that you may end up with multiple copies of the same node, through duplication and such. To
save space, you might want to merge the internal reference counted structure. Obviously, this only
makes a difference if reference counting is turned on.
libjson will try and do this efficiently, merging with the internal structure that has the highest reference
count.
Option Differences
Parameters
node
The node to perform this function on
node2
One of the other nodes to merge with.
Return Value
None
Complexity
Constant
json_preparse
libjson’s lazy parsing makes parsing JSON that is not entirely used very fast, but sometimes you want to
parse it all at once, making the next reads a little faster
Option Differences
Parameters
node
The node to perform this function on
Return Value
None
Complexity
libjson’s built in Base64 encoder will create a JSON_NODE with Base64 encoded binary data, which
allows you to send images and files around. libjson’s Base64 encoder is faster than most others, so it’s
recommended that you use this method rather than other libraries.
Option Differences
JSON_BINARY - this option is required to use this method and the Base64 method
Parameters
node
The node to perform this function on
bin
binary data
bytes
the number of bytes that the binary data is
Return Value
None
Complexity
Will change the node to a different type and do any conversions necessary.
Option Differences
None
Parameters
node
The node to perform this function on
type
New type of node
Return Value
None
Complexity
Constant except for casting a node to array which is linear with respect to json_size.
json_at
Getting a child
This will give you a reference to a child node at a specific location. This is a safe function and will return
zero if you go out of bounds. The returned value is still a child, so do not try and delete the results.
Option Differences
None
Parameters
node
The node to perform this function on
pos
The index of the child node
Return Value
Complexity
Constant
json_get
Getting a child
This will give you a reference to a child node by its name. This is a safe function and will return zero if
that child does not exist. The returned value is still a child, so do not try and delete the results.
Option Differences
None
Parameters
node
The node to perform this function on
name
The name of the child node
Return Value
Complexity
Getting a child
This will give you a reference to a child node by its name. This is a safe function and will return zero if
that child does not exist. The returned value is still a child, so do not try and delete the results.
Option Differences
Parameters
node
The node to perform this function on
name
The name of the child node
Return Value
Complexity
Reserving space
This function reserves children space, this makes the program faster and use less memory as it doesn't
have to keep allocating new memory when it runs out.
Option Differences
Parameters
node
The node to perform this function on
size
The size to reserve
Return Value
None
Complexity
If there is already some children it’s linear with respect to json_size unless the reserved amount is less
than the current capacity, in which case it’s constant. If there are no children, then it’s constant.
json_push_back
void json_push_back(JSONNODE * node, JSONNODE * child);
Adding a child
This function pushes a new child node on the back of the child list. The child is then managed, so do not
try and delete it later.
Option Differences
None
Parameters
node
The node to perform this function on
child
The node to be added as a child
Return Value
None
Complexity
Constant
json_pop_back_at
Getting a child
This will give remove a JSONNODE from it’s parent and return it to you. Because it’s removed from the
parent, you must delete it yourself.
Option Differences
None
Parameters
node
The node to perform this function on
pos
The index of the child node
Return Value
Complexity
Linear based on json_size minus pos. This is because the references of the other children have to be
shifted.
json_pop_back
Getting a child
This will give remove a JSONNODE from it’s parent and return it to you. Because it’s removed from the
parent, you must delete it yourself.
Option Differences
None
Parameters
node
The node to perform this function on
pos
The index of the child node
name
The name of the child node
Return Value
Complexity
Getting a child
This will give remove a JSONNODE from it’s parent and return it to you. Because it’s removed from the
parent, you must delete it yourself.
Option Differences
Parameters
node
The node to perform this function on
name
The name of the child node
Return Value
Complexity
Getting a child
Searches through the children and finds an iterator to it. This function returns json_end if the child does
not exist.
Option Differences
Parameters
node
The node to perform this function on
name
The name of the child node
Return Value
Complexity
Getting a child
Searches through the children and finds an iterator to it. This function returns json_end if the child does
not exist.
Option Differences
Parameters
node
The node to perform this function on
name
The name of the child node
Return Value
Complexity
Removing a child
Erases a single child and returns the iterator to the next one.
Option Differences
Parameters
node
The node to perform this function on
pos
The position of the node that is to be deleted
Return Value
An iterator that points to the child after the deleted one, or json_end
Complexity
Linear based on json_size minus where it starts from due to memory shifting.
json_erase_multi
Removing a child
Erases a single child and returns the iterator to the next one.
Option Differences
Parameters
node
The node to perform this function on
start
The position of starting node to be deleted (inclusively)
end
The position of ending node to be deleted (inclusively)
Return Value
An iterator that points to the child after the deleted one, or json_end
Complexity
Linear based on json_size minus where it starts from due to memory shifting.
json_insert
Adding a child
These functions place a new child into your node before the node pointed to by the iterator. This
functions copy the nodes, they remain where they are as well, so you must delete it.
Option Differences
Parameters
node
The node to perform this function on
pos
The position to insert before
child
The node to be inserted
Return Value
Adding a child
These functions place a new child into your node before the node pointed to by the iterator. This
functions copy the nodes, they remain where they are as well, so you must delete it.
Option Differences
Parameters
node
The node to perform this function on
pos
The position to insert before
start
Position to start copying (inclusively)
end
Position to stop copying (inclusively)
Return Value
Complexity
Linear based on json_size minus where it starts from due to memory shifting plus end minus start for the
ranged variety.
json_begin
This function gets you an iterator pointing to the beginning of the children.
Option Differences
Parameters
node
The node to perform this function on
Return Value
Complexity
Constant
json_end
This function gets you an iterator pointing past the end of the children.
Option Differences
Parameters
node
The node to perform this function on
Return Value
Complexity
Constant
json_lock
Lock a mutex
! This function locks the mutex attached to a node, and locks anything sharing the lock in a
different thread. The reason for the threadID parameter is that because libjson passes around structures
behind the scenes it might be possible to try and lock the same lock in multiple places in the same critical
section. Counting locks per thread eliminates this problem.
Option Differences
Parameters
node
The node to perform this function on
threadID
A unique id for this thread
Return Value
None
Complexity
Constant
json_unlock
Unlock a mutex
! This function unlocks the mutex attached to a node. If the mutex has been locked multiple times
by the same thread, then it will wait until all locks have been released before actually doing the unlock.
Option Differences
Parameters
node
The node to perform this function on
threadID
A unique id for this thread
Return Value
None
Complexity
Constant
json_set_mutex
Set a lock
! This function attaches a mutual exclusion lock for the node. It can be locked and unlocked by
using the lock and unlock functions, The reason for this is that because libjson’s complex reference
counting and internal magic, it is difficult to be sure that you track data correctly, so libjson will pass this
mutex around it’s internal system and track it for you.
! You can pass NULL to this function to unset a mutex.
! This method will filter the mutex down to all children as well, and anything that you add to it later.
Option Differences
Parameters
node
The node to perform this function on
mutex
A pointer to a mutex of any type (POSIX, Windows…)
Return Value
None
Complexity
! This function sets a global mutex for libjson. This is not the same as the manager mutex that you
are required to register in register_mutex_callbacks. This mutex is a fallback mutex that gets locked
when you attempt to lock a node that has no mutex attached to it. You may wish to omit assigning
mutexes for each node and just let them all use the global one.
Option Differences
Parameters
mutex
A mutex that libjson will use when it doesn’t have any to use
Return Value
None
Complexity
Constant
json_parse
JSONNODE * json_parse(const json_char * json);
! This function parses JSON text and returns you a JSONNode which is the root node of the text
that you just passed it. If bad JSON is sent to this method it may return NULL.
Option Differences
JSON_SAFE - a node of type JSON_NULL will be returned if the json was invalid
Parameters
json
JSON text
Return Value
Complexity
! This function parses JSON text and returns you a JSONNode which is the root node of the text
that you just passed it. If bad JSON is sent to this method it may return NULL. This method assumes
that the JSON has no whitespace, or comments.
Option Differences
JSON_SAFE - a node of type JSON_NULL will be returned if the json was invalid
Parameters
json
JSON text
Return Value
Complexity
! This function removes anything that the JSON standard defines as white space, including extra
tabs, spaces, formatting, and comments. This makes this function useful for compressing json that needs
to be stored or sent over a network.
Option Differences
None
Parameters
json
JSON text
Return Value
Complexity
! This function validates the text by parsing it completely and looking for anything that is
malformed.
Option Differences
Parameters
json
JSON text
Return Value
Complexity
Linear depending on strlen(json) and the number of nodes within the text.
json_is_valid_unformatted
json_bool_t json_is_valid_unformatted(const json_char * json);
! This function validates the text by parsing it completely and looking for anything that is
malformed. This is the version to use if your json doesn’t have any white space or comments.
Option Differences
Parameters
json
JSON text
Return Value
Complexity
Linear depending on strlen(json) and the number of nodes within the text.
json_validate (deprecated)
JSONNODE * json_validate(const json_char * json);
! This function validates the text by parsing it completely and looking for anything that is
malformed. If bad JSON is sent to this method it will return NULL, otherwise it will return the parsed
object.
! This function will be removed shortly, you are advised to replace all validate calls to json_is_valid
and json_parse functions.
Option Differences
Parameters
json
JSON text
Return Value
Complexity
Linear depending on strlen(json) and the number of nodes within the text.
json_register_debug_callback
void json_register_debug_callback(json_error_callback_t callback);
! This callback allows libjson to tell you exactly what is going wrong in your software, making
debugging and fixing the problem much easier.
Option Differences
Parameters
callback
A method that must have this prototype: static void callback (const json_char * message)
Return Value
None
Complexity
Constant
json_register_mutex_callbacks
void json_register_mutex_callbacks(json_mutex_callback_t lock, json_mutex_callback_t unlock, void *
manager_mutex);
void json_register_mutex_callbacks(json_mutex_callback_t lock, json_mutex_callback_t unlock,
json_mutex_callback_t destroy, void * manager_mutex);
! This callback allows libjson to lock mutexes that you assign to JSONNode structures. Because
libjson has no idea what kind of mutex you gave it, it can’t lock it without the help of a callback. This
method is required to run before any locking can take place.
Option Differences
Parameters
lock
A method that locks a mutex and must have this prototype: static void callback (void * mutex).
unlock
A method that unlocks a mutex and must have this prototype: static void callback (void * mutex).
destroy
A method that deletes a mutex and must have this prototype: static void callback (void * mutex).
This parameter is only allowed if JSON_MUTEX_MANAGER is defined, otherwise, you are
responsible for cleaning up you mutexes.
manager_mutex
A mutex that libjson will need to use to handle all of the mutexes, as even without
JSON_MUTEX_MANAGER, some management takes place and libjson has a few critical
sections when threading. May not be the same as the global mutex.
Return Value
None
Complexity
Constant
json_register_memory_callbacks
void json_register_memory_callbacks(json_malloc_t allocer, json_realloc_t reallocer, json_free_t freer);
! This function sets callbacks that libjson will use to allocate memory. This allows you to keep a
tight control of memory allocation, or use things like memory pool and such. These methods are currently
not allowed to return null or less than it asked for, as it will cause instability in libjson.
Option Differences
Parameters
allocer
A method that must have this prototype: static void * alloc(unsigned long bytes)
reallocer
A method that must have this prototype: static void * realloc(void * buffer, unsigned long bytes)
freer
A method that must have this prototype: static void dealloc(void * buffer)
Return Value
None
Complexity
Constant
json_free
void json_free(void * str);
Frees text
! This function removes the memory allocated by various functions that return strings, such as
json_as_string, json_as_binary, json_write…
Option Differences
None
Parameters
str
Memory that libjson allocated
Return Value
None
Complexity
Constant unless JSON_MEMORY_MANAGE is defined in which case it’s logarithmic depending on the
number of strings currently allocated.
json_free_all
void json_free_all(void);
Frees text
! This function removes all of the memory that libjson has allocated for strings and binary. This
allows for bulk frees and garbage collection.
Option Differences
Parameters
None
Return Value
None
Complexity
Constant
json_encode64
json_char * json_encode64(const void * binary, json_index_t bytes);
Encodes data
! This function takes binary data and does a base64 encoding so that you can send it through a
text only protocol,
Option Differences
Parameters
binary
! binary data
bytes
! the number of bytes in the binary buffer
Return Value
Complexity
Linear
json_decode64
void * json_decode64(const json_char * text, unsigned long * bytes);
Encodes data
! This function takes base64 encoded data and decodes it for you
Option Differences
Parameters
text
! base64 encoded text
bytes
! the number of bytes in the returned binary buffer
Return Value
Decoded binary data. Note: This is raw data, it is NOT a null terminated string
Complexity
Linear
JSON_TEXT
Converts text
! This is a marco that you can use to wrap around text that you pass into libjson. It automatically
prepends an L in unicode mode and does nothing when not in unicode mode. This allows you to use the
same code for unicode and non unicode software.
C++ interface
! libjson has an interface specifically designed for C++. It’s designed for the following things:
speed, heavy internal optimization, and ease of use. The interface should be very intuitive to those
familiar with STL and uses standard overloaded operators.
! Because so many of the functions in JSONNode are inline, the merge between your program and
the library at the optimization level allows more optimization that if the library was external. Your program
will run faster and use less memory because of this.
! There are two main interfaces here: libjson and JSONNode. libjson is for parsing and registering
callbacks and JSONNode is the worker and the structure that stores and manipulates JSON once it’s
been loaded.
! This part of the document is set up to look like cplusplus.com’s reference manual, so that it
should be easy to navigate and find everything that you’re looking for.
JSONNode
! JSONNode is the basic class for holding JSON values. It is a reference-counted, copy-on-write
class that adheres to standard C++ practices. It has a very small footprint, both in memory and on the
processor. It's interface is similar to anything in STL, and should be very intuitive.
! There are several types of JSONNodes, but they all share the same class.
JSONNode types
Function Description
JSON_STRING A string
Member types
Function Description
Function Description
Inspector functions
Function Description
Comparison Functions
Function Description
Function Description
Function Description
Function Description
Function Description
Text Functions
Function Description
Construct JSONNode
Constructs a JSONNode object, initializing it's contents depending on which constructor is used:
Option differences
JSON_REF_COUNT - if this is turned off, the copy constructor will fully duplicate the node
JSON_ISO_STRICT will remove the long long and long double variants
Parameters
mytype
The enumerated type of the JSONNode.
name_t
! The name of the object
value_t
! The value of the object
orig
! The original JSONNode that gets copied
Complexity
~JSONNode(void);
Destruct JSONNode
Option Differences
None
Parameters
None
Complexity
! Depends on circumstances. If it's reference count is not one, then it's complexity is constant, if
it's the sole owner of it's value, then it becomes linear on JSONNode::size, however, because JSON is a
tree structure it's worse case scenario is linear on JSONNode::size + JSONNode::size of each child
recursively.
JSONNode::duplicate
JSONNode duplicate(void);
Duplicating JSONNode
! Constructs a JSONNode object, by copying the contents of JSONNode. This is different from the
copy constructor or assignment operator because it makes a literal copy, not reference counting.
Option Differences
None
Parameters
None
Return Value
Complexity
Linear on JSONNode::size, however, because JSON is a tree structure it's worse case scenario is linear
on JSONNode::size + JSONNode::size of each child recursively.
JSONNode::operator =
Assign JSONNode
Assigns JSONNode to a specific value and sets the type according to which version is used:
Option Differences
JSON_REF_COUNT - if this is off, then the copy assignment will fully duplicate the node
JSON_ISO_STRICT will remove the long long and long double variants
Parameters
value_t
! The value of the object
orig
! The original JSONNode that gets copied
Complexity
! All assignments run in constant time due to reference counting, if reference counting is not turned
on, then the copy assignment is the same as duplicate.
JSONNode::operator ==
Comparing JSONNode
! Checks if the value held within the nodes are equal. This ignores things like comments, but for
JSON_NODE and JSON_ARRAYs, this is a deep comparison, checking each child too.
Option Differences
JSON_ISO_STRICT will remove the long long and long double variants
Parameters
value_t
! The value to compare to
node
! Another node to compare to
Complexity
! Constant except for JSON_NODEs and JSON_ARRAYs in which case it’s linear with respect to
size() and size() of each child recursively.
JSONNode::operator !=
Comparing JSONNode
! Checks if the value held within the nodes are not equal. This ignores things like comments, but
for JSON_NODE and JSON_ARRAYs, this is a deep comparison, checking each child too.
Option Differences
JSON_ISO_STRICT will remove the long long and long double variants
Parameters
value_t
! The value to compare to
node
! Another node to compare to
Complexity
! Constant except for JSON_NODEs and JSON_ARRAYs in which case it’s linear with respect to
size() and size() of each child recursively.
JSONNode::type
char type(void);
Return type
Option Differences
None
Parameters
none
Return Value
Complexity
Constant
JSONNode::size
size_t size(void);
Return size
Returns the number of children that the node has. This should be zero for anything other than
JSON_ARRAY or JSON_NODE, but this is only guaranteed with the JSON_SAFE option turned on. This
is because casting may or may not purge the children.
Option Differences
None
Parameters
None
Return Value
Complexity
Constant.
JSONNode::empty
bool empty(void);
Return empty
Returns whether or not the node has any children. If the node is not of JSON_NODE or JSON_ARRAY it
will invariably return true.
Option Differences
None
Parameters
None
Return Value
Complexity
Constant.
JSONNode::name
json_string name(void);
Return name
Returns the name of the node. If there is no name, then it returns a blank string.
Option Differences
None
Parameters
None
Return Value
Complexity
Constant.
JSONNode::get_comment
json_string get_comment(void);
Return comment
Option Differences
Parameters
None
Return Value
Complexity
Constant.
JSONNode::as_string
json_string as_string(void);
Returns the string representation of the node. This may be different depending on the type of the node
Function Description
JSON_ARRAY “”
JSON_NODE “”
Notice that both JSON_NODE and JSON_ARRAY return empty strings. Use JSONNode::write and
JSONNode::write_formatted to output JSON.
Option Differences
JSON_CASTABLE - if this option is turned on, all return values are undefined except for JSON_STRING
Parameters
None
Return Value
Complexity
Constant.
JSONNode::as_int
json_int_t as_int(void);
Returns the boolean representation of the node. This may be different depending on the type of the node
Function Description
JSON_NULL 0
JSON_STRING Undefined
JSON_ARRAY Undefined
JSON_NODE Undefined
If the value is actually a floating point value, then libjson will record an error via it's callback, but will
continue on ahead and simply truncate the value. So 15.9 will be returned as 15. If JSON_DEBUG is
turned on, it will also error if the value of the node is outside the range of the long datatype.
Option Differences
Parameters
None
Return Value
Complexity
Constant.
JSONNode::as_float
json_number as_float(void);
Returns the boolean representation of the node. This may be different depending on the type of the node
Function Description
JSON_NULL 0.0
JSON_STRING Undefined
JSON_NUMBER Value
JSON_ARRAY Undefined
JSON_NODE Undefined
Option Differences
JSON_CASTABLE - if this option is turned on, all return values are undefined except for JSON_NUMBER
Parameters
None
Return Value
Complexity
Constant.
JSONNode::as_bool
bool as_bool(void);
Returns the boolean representation of the node. This may be different depending on the type of the node
Function Description
JSON_NULL FALSE
JSON_STRING Undefined
JSON_BOOL Value
JSON_ARRAY Undefined
JSON_NODE Undefined
Option Differences
JSON_CASTABLE - if this option is turned on, all return values are undefined except for JSON_BOOL
Parameters
None
Return Value
Complexity
Constant.
JSONNode::as_node
JSONNode as_node(void);
Returns the node representation of the node. For anything other than node and array, it simply returns an
empty node. If the caller is an array, it will convert it to a node.
Function Description
Option Differences
None
Parameters
None
Return Value
Complexity
Constant for all except JSON_ARRAYs and JSON_NODEs which are the same as the copy constructor.
JSONNode::as_array
JSONNode as_array(void);
Returns the array representation of the node. For anything other than node and array, it simply returns an
empty array. If the caller is an node, it will convert it to an array by stripping all of the names of each
child.
Function Description
Option Differences
None
Parameters
None
Return Value
Complexity
Constant for anything other than a node. For a JSON_NODE, it is linear with respect to JSONNode::size,
and JSON_ARRAY which is the same as the copy constructor
JSONNode::as_binary
std::string as_binary(void);
Returns the binary value that was part of this node. It returns it as a std::string, you can use the data()
function to retrieve it in binary form. This allows you to use size() to know how large the binary data is.
Function Description
JSON_NULL Undefined
JSON_NUMBER Undefined
JSON_BOOL Undefined
JSON_ARRAY Undefined
JSON_NODE Undefined
Option Differences
JSON_BINARY - If this option is not on, then this function is not accessible.
Parameters
None
Return Value
Complexity
Returns a JSONNode that exposes all of the inner members of JSONNode. This is useful for debugging
purposes of libjson, but not much else. It is mostly used to maintain and upgrade libjson.
Option Differences
JSON_DEBUG - If this option is not on, then this function is not accessible.
Parameters
None
Return Value
A JSONNode representation of the inner workers of the JSONNode, showing all of the members and their
current state.
Complexity
Linear with respect to the size of the tree underneath the node.
JSONNode::write
json_string write(size_t approxsize = DEFAULT_APPROX_SIZE) const;
Write JSON
Returns JSON text, with no white space or comments. Designed to create JSON that is very small, and
therefore, faster to send between servers or write to a disk. The flipside is that it’s nearly impossible to
read by human eyes.
Only root nodes (JSON_NODE and JSON_ARRAYs) are meant to be written, all others will return a blank
string.
Option Differences
JSON_WRITER - If this option is not on, then this function is not accessible.
Parameters
approxsize
The size that you want to start the buffer at. If omitted, libjson assigns a default value based on
the compiling options. This is just an estimated size, libjson will extend the buffer if it needs to.
Return Value
Complexity
Linear with respect to the size of the tree underneath the node.
JSONNode::write_formatted
json_string write_formatted(size_t approxsize = DEFAULT_APPROX_SIZE_FORMATTED) const;
Write JSON
Returns JSON text that has been indented and prettied up so that it can be easily read and modified by
humans.
Only root nodes (JSON_NODE and JSON_ARRAYs) are meant to be written, all others will return a blank
string.
Option Differences
JSON_WRITER - If this option is not on, then this function is not accessible.
JSON_COMMENTS - If this option is not turned on, the no comments are written
JSON_WRITE_BASH_COMMENTS - This option will make libjson write only bash style # comments
JSON_WRITE_SINGLE_LINE_COMMENTS - This option will make libjson not write C-style /* */
comments
Parameters
approxsize
The size that you want to start the buffer at. If omitted, libjson assigns a default value based on
the compiling options. This is just an estimated size, libjson will extend the buffer if it needs to.
Return Value
Complexity
Linear with respect to the size of the tree underneath the node.
JSONNode::set_name
void set_name(json_string name_t);
Option Differences
None
Parameters
name_t
The name of the node
Return Value
None
Complexity
Constant
JSONNode::set_comment
void set_comment(json_string comment_t);
Option Differences
Parameters
comment_t
The comment attached to the node
Return Value
None
Complexity
Constant
JSONNode::clear
void clear(void);
Clearing a node
Option Differences
None
Parameters
None
Return Value
None
Complexity
Swaps the contents of two nodes. This is very fast because JSONNode is just a wrapper around an
internal structure, so it simply swaps pointers to those structures.
Option Differences
None
Parameters
other
The node to swap values with
Return Value
None
Complexity
Constant
JSONNode::merge
void merge(JSONNode & other);
void merge(unsigned int num, . . .);
It’s possible that you may end up with multiple copies of the same node, through duplication and such. To
save space, you might want to merge the internal reference counted structure. Obviously, this only
makes a difference if reference counting is turned on.
libjson will try and do this efficiently, merging with the internal structure that has the highest reference
count.
Option Differences
Parameters
other
One of the other nodes to merge with.
num
The number of JSONNodes to merge together
...
A list of JSONNode *
Return Value
None
Complexity
libjson’s lazy parsing makes parsing JSON that is not entirely used very fast, but sometimes you want to
parse it all at once, making the next reads a little faster
Option Differences
Parameters
None
Return Value
None
Complexity
libjson’s built in Base64 encoder will create a JSON_NODE with Base64 encoded binary data, which
allows you to send images and files around. libjson’s Base64 encoder is faster than most others, so it’s
recommended that you use this method rather than other libraries.
Option Differences
JSON_BINARY - this option is required to use this method and the Base64 method
Parameters
bin
binary data
bytes
the number of bytes that the binary data is
Return Value
None
Complexity
Will change the node to a different type and do any conversions necessary.
Option Differences
None
Parameters
type
New type of node
Return Value
None
Complexity
Constant except for casting a node to array which is linear with respect to size().
JSONNode::at
JSONNode & at(json_index_t pos) throw(std::out_of_range);
JSONNode & at(const json_string & name) throw(std::out_of_range);
const JSONNode & at(json_index_t pos) const throw(std::out_of_range);
const JSONNode & at(const json_string & name) const throw(std::out_of_range);
Getting a child
This will give you a reference to a child node either at a specific location or by it’s name. This differs from
the [] operator because at will throw an std::out_of_bounds exception.
Option Differences
None
Parameters
pos
The index of the child node
name
The name of the child node
Return Value
Complexity
Constant for the indexed variety, linear for the named variety.
JSONNode::at_nocase
JSONNode & at_nocase(const json_string & name) throw(std::out_of_range);
const JSONNode & at_nocase(const json_string & name) const throw(std::out_of_range);
This will give you a reference to a child node by it’s name in a case-insensitive way.
Option Differences
Parameters
name
The name of the child node
Return Value
Complexity
Getting a child
This will give you a reference to a child node either at a specific location or by it’s name. Asking for a
node that is not there will result in undefined behavior.
Option Differences
None
Parameters
pos
The index of the child node
name
The name of the child node
Return Value
Complexity
Constant for the indexed variety, linear for the named variety.
JSONNode::reserve
Reserving space
This function reserves children space, this makes the program faster and use less memory as it doesn't
have to keep allocating new memory when it runs out.
Option Differences
None
Parameters
size
The size to reserve
Return Value
None
Complexity
If there is already some children it’s linear with respect to size() unless the reserved amount is less than
the current capacity, in which case it’s constant. If there are no children, then it’s constant.
JSONNode::push_back
void push_back(const JSONNode & node);
Adding a child
This function pushes a new child node on the back of the child list. This method copies the child, so
altering the parameter later will not affect the one in the children.
Option Differences
None
Parameters
node
The node to be added as a child
Return Value
None
Complexity
Depends on if new memory is needed to be allocated. This function would have the same complexity as
push_back for a vector plus the copy constructor. If JSON_LESS_MEMORY is defined, then this
operation is always linear with respect to size(), unless reserve had been used, in which case it’s constant
while smaller than that reserved amount . Otherwise it is linear if the node is currently full, otherwise it’s
constant.
JSONNode::pop_back
Getting a child
This will give remove a JSONNode from it’s parent and return it to you.
Option Differences
None
Parameters
pos
The index of the child node
name
The name of the child node
Return Value
Complexity
Linear based on size() for the variety using the name, but linear based on size() minus pos. This is
because the references of the other children have to be shifted.
JSONNode::pop_back_nocase
JSONNode pop_back_nocase(const json_string & name) throw(std::out_of_range);
Getting a child
This will give remove a JSONNode from it’s parent and return it to you.
Option Differences
Parameters
name
The name of the child node
Return Value
Complexity
Getting a child
Searches through the children and finds an iterator to it. This function returns JSONNode::end() if the
child does not exist.
Option Differences
Parameters
name
The name of the child node
Return Value
Complexity
Getting a child
Searches through the children and finds an iterator to it. This function returns JSONNode::end() if the
child does not exist.
Option Differences
Parameters
name
The name of the child node
Return Value
Complexity
Removing child(ren)
Option Differences
Parameters
pos
The position of the node that is to be deleted
start
The position of starting node to be deleted (inclusively)
end
The position of ending node to be deleted (inclusively)
Return Value
An iterator that points to the child after the deleted one, or end()/rend()
Complexity
Linear based on size() minus where it starts from due to memory shifting.
JSONNode::insert
iterator insert(iterator pos, const JSONNode & node);
iterator insert(iterator pos, const iterator & start, const iterator & end);
iterator insert(iterator pos, const reverse_iterator & start, const reverse_iterator & end);
iterator insert(iterator pos, const const_iterator & start, const const_iterator & end);
iterator insert(iterator pos, const const_reverse_iterator & start, const const_reverse_iterator & end);
reverse_iterator insert(reverse_iterator pos, const JSONNode & node);
reverse_iterator insert(reverse_iterator pos, const reverse_iterator & start, const reverse_iterator & end);
reverse_iterator insert(iterator pos, const iterator & start, const iterator & end);
reverse_iterator insert(reverse_iterator pos, const const_iterator & start, const const_iterator & end);
reverse_iterator insert(reverse_iterator pos, const const_reverse_iterator & start, const
const_reverse_iterator & end);
Adding child(ren)
All of these functions copy the nodes, they remain where they are as well.
Option Differences
Parameters
pos
The position to insert before
node
The node to be inserted
start
Position to start copying (inclusively)
end
Position to stop copying (inclusively)
Return Value
Linear based on size() minus where it starts from due to memory shifting plus end minus start for the
ranged variety.
JSONNode::begin
iterator begin(void);
const_iterator begin(void) const;
This function gets you an iterator pointing to the beginning of the children.
Option Differences
Parameters
None
Return Value
Complexity
Constant
JSONNode::end
iterator end(void);
const_iterator end(void) const;
This function gets you an iterator pointing past the end of the children.
Option Differences
Parameters
None
Return Value
Complexity
Constant
JSONNode::rbegin
reverse_iterator rbegin(void);
reverse_const_iterator rbegin(void) const;
This function gets you an iterator pointing to the beginning of the children in reverse order.
Option Differences
Parameters
None
Return Value
An iterator that points to the first child in reverse order (actually the last child.)
Complexity
Constant
JSONNode::rend
reverse_iterator rend(void);
reverse_const_iterator rend(void) const;
This function gets you an iterator pointing past the end of the children in reverse order
Option Differences
Parameters
None
Return Value
Complexity
Constant
JSONNode::set_mutex
void set_mutex(void * mutex);
Set a lock
! This function attaches a mutual exclusion lock for the node. It can be locked and unlocked by
using the lock and unlock functions, The reason for this is that because libjson’s complex reference
counting and internal magic, it is difficult to be sure that you track data correctly, so libjson will pass this
mutex around it’s internal system and track it for you.
! You can pass NULL to this function to unset a mutex.
! This method will filter the mutex down to all children as well, and anything that you add to it later.
Option Differences
Parameters
mutex
A pointer to a mutex of any type (POSIX, Windows…)
Return Value
None
Complexity
Lock a mutex
! This function locks the mutex attached to a node, and locks anything sharing the lock in a
different thread. The reason for the threadID parameter is that because libjson passes around structures
behind the scenes it might be possible to try and lock the same lock in multiple places in the same critical
section. Counting locks per thread eliminates this problem.
Option Differences
Parameters
threadID
A unique id for this thread
Return Value
None
Complexity
Constant
JSONNode::unlock
void unlock(int threadID);
Unlock a mutex
! This function unlocks the mutex attached to a node. If the mutex has been locked multiple times
by the same thread, then it will wait until all locks have been released before actually doing the unlock.
Option Differences
Parameters
threadID
A unique id for this thread
Return Value
None
Complexity
Constant
JSONStream
! JSONStreams allow you to have partial json or multiple json objects and alert you when the
nodes are completed.
Class Functions
Function Description
New Stream
! This function creates a stream. Streams are used for pushing small amounts of json at a time, it
may be incomplete json, or even multiple json nodes, and the callback you give it will be called whenever
a complete node is recognized.
Option Differences
Parameters
callback
The method that gets called whenever nodes are completed
e_callback
The method that gets called the stream encounters bad json
id
The pointer to pass into the callback, JSONSTREAM_SELF will tell it to use itself
orig
! The stream to copy
Return Value
A new stream
Complexity
Constant
JSONStream::~JSONStream
~JSONStream(void);
Deletes stream
Option Differences
Parameters
None
Return Value
None
Complexity
Constant
JSONStream::operator =
Copies a stream
Copies a stream
Option Differences
Parameters
orig
! The node to copy
Return Value
A reference to itself
Complexity
Constant
JSONStream::operator <<
Push to a stream
This pushes a string on the stream, and if a node gets completed, the callback gets called.
Option Differences
Parameters
str
! Partial json
Return Value
A reference to itself
Complexity
Constant
JSONStream::reset
void reset(void);
Resets to a stream
Resets a stream
Option Differences
Parameters
none
Complexity
Constant
libjson
! libjson is a namespace that holds a few functions that are part of libjson, but separate from
JSONNode. These methods include json text functions and callback registration.
JSON Functions
Function Description
Callback Registration
Function Description
Base64 Functions
Function Description
Callback Types
Function Description
! This function parses JSON text and returns you a JSONNode which is the root node of the text
that you just passed it. If bad JSON is sent to this method it will throw a std::invalid_argument exception.
Option Differences
JSON_SAFE - a node of type JSON_NULL will be returned if the json was invalid
Parameters
json
JSON text
Return Value
Complexity
! This function parses JSON text and returns you a JSONNode which is the root node of the text
that you just passed it. If bad JSON is sent to this method it will throw a std::invalid_argument exception.
Option Differences
JSON_SAFE - a node of type JSON_NULL will be returned if the json was invalid
Parameters
json
JSON text
Return Value
Complexity
! This function removes anything that the JSON standard defines as white space, including extra
tabs, spaces, formatting, and comments. This makes this function useful for compressing json that needs
to be stored or sent over a network.
Option Differences
None
Parameters
json
JSON text
Return Value
Complexity
! This function validates the text by parsing it completely and looking for anything that is
malformed.
Option Differences
Parameters
json
JSON text
Return Value
true or false
Complexity
Linear depending on json.length() and the number of nodes within the text.
libjson::is_valid_unformatted
bool is_valid_unformatted(const json_string & json);
! This function validates the text by parsing it completely and looking for anything that is
malformed. This is the version for json that doesn’t have any white space or comments.
Option Differences
Parameters
json
JSON text
Return Value
true or false
Complexity
Linear depending on json.length() and the number of nodes within the text.
libjson::validate (deprecated)
JSONNode validate(const json_string & json);
! This function validates the text by parsing it completely and looking for anything that is
malformed. If bad JSON is sent to this method it will throw a std::invalid_argument exception, otherwise it
returns the root node of the text.
! This function will be removed shortly, you are advised to replace all validate calls to is_valid and
parse functions.
Option Differences
Parameters
json
JSON text
Return Value
Complexity
Linear depending on json.length() and the number of nodes within the text.
libjson::register_debug_callback
void register_debug_callback(json_error_callback_t callback);
! This callback allows libjson to tell you exactly what is going wrong in your software, making
debugging and fixing the problem much easier.
Option Differences
Parameters
callback
A method that must have this prototype: static void callback (const json_string & message)
Return Value
None
Complexity
Constant
libjson::register_mutex_callbacks
void register_mutex_callbacks(json_mutex_callback_t lock, json_mutex_callback_t unlock, void *
manager_mutex);
void register_mutex_callbacks(json_mutex_callback_t lock, json_mutex_callback_t unlock,
json_mutex_callback_t destroy, void * manager_mutex);
! This callback allows libjson to lock mutexes that you assign to JSONNode structures. Because
libjson has no idea what kind of mutex you gave it, it can’t lock it without the help of a callback. This
method is required to run before any locking can take place.
Option Differences
Parameters
lock
A method that locks a mutex and must have this prototype: static void callback (void * mutex).
unlock
A method that unlocks a mutex and must have this prototype: static void callback (void * mutex).
destroy
A method that deletes a mutex and must have this prototype: static void callback (void * mutex).
This parameter is only allowed if JSON_MUTEX_MANAGER is defined, otherwise, you are
responsible for cleaning up you mutexes.
manager_mutex
A mutex that libjson will need to use to handle all of the mutexes, as even without
JSON_MUTEX_MANAGER, some management takes place and libjson has a few critical
sections when threading. May not be the same as the global mutex.
Return Value
None
Complexity
Constant
libjson::set_global_mutex
void set_global_mutex(void * mutex);
! This function sets a global mutex for libjson. This is not the same as the manager mutex that you
are required to register in register_mutex_callbacks. This mutex is a fallback mutex that gets locked
when you attempt to lock a node that has no mutex attached to it. You may wish to omit assigning
mutexes for each node and just let them all use the global one.
Option Differences
Parameters
mutex
A mutex that libjson will use when it doesn’t have any to use
Return Value
None
Complexity
Constant
libjson::register_memory_callbacks
void register_memory_callbacks(json_malloc_t allocer, json_realloc_t reallocer, json_free_t freer);
! This function sets callbacks that libjson will use to allocate memory. This allows you to keep a
tight control of memory allocation, or use things like memory pool and such. These methods are currently
not allowed to return null or less than it asked for, as it will cause instability in libjson.
Option Differences
Parameters
allocer
A method that must have this prototype: static void * alloc(size_t bytes)
reallocer
A method that must have this prototype: static void * realloc(void * buffer, size_t bytes)
freer
A method that must have this prototype: static void dealloc(void * buffer)
Return Value
None
Complexity
Constant
libjson::encode64
json_string encode64(const unsigned char * binary, json_index_t bytes);
Encodes data
! This function takes binary data and does a base64 encoding so that you can send it through a
text only protocol,
Option Differences
Parameters
binary
! binary data
bytes
! the number of bytes in the binary buffer
Return Value
Complexity
Linear
libjson::decode64
unsigned char * decode64(const json_string & text, unsigned long * bytes);
Encodes data
! This function takes base64 encoded data and decodes it for you
Option Differences
Parameters
text
! base64 encoded text
bytes
! the number of bytes in the returned binary buffer
Return Value
Decoded binary. Note: This is raw data, not a null terminated string
Complexity
Linear
libjson::to_std_string
std::string to_std_string(const json_string & str);
Option Differences
Parameters
str
! The string to be converted
Return Value
The string in std::string. Note that if you are in unicode mode, some information may get lost.
Complexity
Option Differences
Parameters
str
! The string to be converted
Return Value
Complexity
! This function takes a STL string and converts to it a json_string for you
Option Differences
Parameters
str
! The string to be converted
Return Value
The string in json_string. Note that if you go from unicode to non-unicode, you may loose information.
Complexity
Converts text
! This is a marco that you can use to wrap around text that you pass into libjson. It automatically
prepends an L in unicode mode and does nothing when not in unicode mode. This allows you to use the
same code for unicode and non unicode software.
Optimizing libjson
! Once your program is written and functioning with libjson, it is time to optimize it. libjson’s options
are the best way to do this, however if you are using a library, then you can also edit the make file and
change the compiler options. Obviously you should never try to optimize with a debug build, it’s doing a
lot of extra checks that help debugging, but are unneeded in release.
Compiler Options
! You can see the default compiler options in the building libjson section of this document. -O3 isn’t
always optimal, because it’s such a small library, caching may actually make -Os the fastest, it depends
on how much cache you have, what kind of computer, and what libjson options are turned on.
! There are also many optimizations that you can do that are compiler specific. libjson does a
decent amount of string functions internally, so turning on reference counted or copy on write strings may
result in a performance increase, both faster due to less copying and less memory.
C++ Optimizations
! If using C++, you can embed libjson and compile it into your program. This saves any time at the
interface. The C interface is fairly rigid, and everything has to pass through the library interface, creating
a choke-point. But in C++, many of the functions get inlined, so that little extra overhead is gone. The
compiler is also free to do things like return by reference and other little tricks that you can’t get with the
json_ interface.
!
JSONOptions.h Optimizations
! You can also optimize libjson by changing the options. Here are some common optimizations.
Speed
! If you know that you will always be receiving proper json, or json written by your libjson engine
(like if you are using it to store and read a configuration file), then JSON_SAFE is probably not needed.
That option does a lot of checks to make sure that the json isn’t corrupt and guards if it is. If there is no
need for these guards, don’t bother with them.
! If you are not always sure that the json is valid, but need more parsing speed. turn JSON_SAFE
off and validate the json before sending it to the parser.
! The JSON_MEMORY_CALLBACKS option can help you dramatically speed up your program.
libjson allocates a lot of memory using malloc, but those calls can be rerouted to callbacks, allowing you
to utilize your own memory management system. A memory pool can speed up a program.
! Starting with libjson 7.4.0, libjson has a built in memory pool that is shut off by default.
Uncomment the JSON_MEMORY_POOL option, and if necessary, change it’s starting pool size. In tests,
memory pooling increased speed performance by 30%.
! Starting with libjson 6.3.0, you can have libjson compile some parts of itself differently than other
parts. If your program is mostly using libjson for reading, you should set JSON_READ_PRIORITY to
HIGH. If you are mostly writing set JSON_WRITE_PRIORITY to HIGH. If you almost never write, turn it
to LOW. This is can create some dramatically different code on certain compilers.
Memory
! If JSON_STDERROR is on, libjson prints out any errors to std::cerr, which requires iostream.
iostream adds considerable size to the library. Removing the JSON_STDERROR option will compile the
library without iostream in it.
! If you are parsing huge amounts of JSON, or are working with very limited memory and need
libjson to use less of it, turn on the JSON_LESS_MEMORY option. This will cause libjson to be far more
stringent with it’s memory and clean it up faster. It also makes it slightly slower though because it
allocates and deallocates memory more often.
! Manage your own memory. Turn JSON_MEMORY_MANAGE off if you turned it on and delete
your memory when you are done using it instead of just letting it sit around. libjson utilizes a map to keep
track of memory, this can grow quiet a bit if not flushed often enough. Managed memory is in libjson for
ease of use, not performance.
! If you can bring down the size of the indexes, it may save some bytes. By turning on and
changing the JSON_INDEX_TYPE option, you can choose a different type of all of the indexing. This
cuts down on the size of the internal structure, but be careful, you have to give enough space to hold all
of your nodes. If you are sure that no node will ever hold more than 255 subitems, you can even use an
unsigned char.
! You might be able to further decrease the memory required and the size of the library if you use
your own string class. JSON_STRING_HEADER lets you drop in your own string class which you can
heavily optimize for your needs. A string class that does reference counting, or even shallow substrings
could dramatically reduce your memory usage.
! Remove the JSON_CASTABLE option if you can. This option allows libjson to do conversions to
do be a lot more flexible, however, if you don’t ever use these conversions, or do so rarely, you may get a
small memory drop if you turn it off, as it will no longer keep a string version of numbers, and bools, and
nulls, and it may also significantly reduce the size of the binary.
! Turn off all optional features that you are not using. The defaults in the options are meant to be
flexible and easy to use, so it has a lot of functions available. For example, there are deprecated
functions available in the default libjson.
Overall
! If your program almost always uses most or all of the json that it receives, then doing parsing as
needed might not make sense, and you might want all parsing done at once. JSON_PREPARSE will
force libjson to do this. This makes the initial parse command a little slower, but every subsequent
request is faster. It also drops the amount of memory libjson uses slightly.
! If you turned JSON_REF_COUNT off, and can find a way to turn it back on, do it. This cuts down
on both the amount of memory used when copying objects, but also saves copy time, which sometimes
can be quite expensive. The common reason to turn this option off is for thread safety. It is
recommended that you use the mutex callback system instead.
! Write your own string class, or find a better one. There are many string classes out there that
perform better than STL in some cases and are drop in and forget. Define JSON_STRING_HEADER to
point to a header where you typedef your replacement string as json_string. libjson has no control over
how the strings work, so you can often specialize a string type for this case. The majority of both time
and memory used by libjson is spent doing string manipulation.
! Benchmark your software doing both preparsing and JiT parsing. Often, if you are using all of the
JSON, preparsing the JSON is both faster and uses a smaller footprint.
Roadmap
This is the roadmap of things coming down the pipeline. Bug fixes and other mistakes
are always fixed as quickly as possible, but other projects that require more time, and
possibly a phased rollout are jotted down here.
Redistribution and use in source and binary forms, with or without modification, are
permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of
conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this
list of conditions and the following disclaimer in the documentation and/or other
materials provided with the distribution.
The views and conclusions contained in the software and documentation are those of
the authors and should not be interpreted as representing official policies, either
expressed or implied, of Jonathan Wallace.