Copyright © 2009-2010 Cybozu Labs, Inc. Copyright © 2011-2015 Kazuho Oku
Licensed under 2-clause BSD license
1.3.1-dev
PicoJSON is a tiny JSON parser / serializer for C++ with following properties:
There are several ways to use the pull (DOM-like) interface of picojson.
The easiest way is to use the two-argument parse
function.
std::string json = "[ \"hello JSON\" ]";
picojson::value v;
std::string err = picojson::parse(v, json);
if (! err.empty()) {
std:cerr << err << std::endl;
}
Four-argument parse
function accepts a pair of iterators, and returns the end position of the input.
const char* json = "{\"a\":1}";
picojson::value v;
std::string err;
const char* json_end = picojson::parse(v, json, json + strlen(json), &err);
if (! err.empty()) {
std::cerr << err << std::endl;
}
std::istream_iterator input(std::cin);
picojson::value v;
std::string err;
input = picojson::parse(v, input, std::istream_iterator(), &err);
if (! err.empty()) {
std::cerr << err << std::endl;
}
It is also possible to use the >>
operator to parse the input, however this interface is not thread-safe.
picosjon::value v;
std::cin >> v;
std::string err = picojson::get_last_error();
Values of a JSON object is represented as instances of picojson::value class.
The code below parses a JSON string and prints the contents of the object.
Please note that the type check is mandatory; do not forget to check the type of the object by calling is<type>() before accessing the value by calling get<type>().
Please refer to the implementation of picojson::default_parse_context and picojson::null_parse_context. There is also an example (examples/streaming.cc) .
Instances of the picojson::value class can be serialized in three ways, to ostream, to std::string, or to an output iterator.
Experimental suport for int64_t becomes available if the code is compiled with preprocessor macro PICOJSON_USE_INT64
.
Turning on the feature will cause following changes to picojson:
picojson::value(int64_t)
is definedis<int64_t>()
and get<int64_t>()
become available.
nor e
/E
are considered as int64 typedouble
s as well (i.e. all values which are .is<int64_t>() == true
are also .is<double>() == true
)get<double>()
is calledEnabling the feature should not cause compatibility problem with code that do not use the feature.
Examples can be found in the examples directory, and on the Wiki. Please add your favorite examples to the Wiki.