nosjob

nosjob
Login

nosjob

nosjob: a C++ library for working with JSON data

Welcome to nosjob, a C++ library for generating and consuming JSON data.

The name "nosjob" (pronounced "nose job") came about one early morning after about 12 hours of hacking. My tired eyes looked on the words "JSON object" and briefly read them as "NOSJ ob..." And so the name was chosen. (There are probably already ten other JSON/C++ toolkits with the name "jsonpp," which was my initial choice of names.)

License: the core code is released into the Public Domain, but the stuff under src/utf8/ and src/parser/ were written by other people and have BSD-like licenses ("do whatever you want with the code, but don't remove the copyright notice").

Author: Stephan Beal (https://wanderinghorse.net/home/stephan/)

Requirements:

A small amount of 3rd-party code is also required, but is included in this source tree.

Primary Features

Primary Misfeatures

Examples

Reading from JSON input:

Atom root = JsonParser().parse( std::cin ); // throws on error
typedef Utf8String STR;
if( Object::isObject(root) ) {
    Object obj = Object::cast(root);
    //... fetch data from the object like so ...
    Atom a = obj.get(STR("myKey"));
    if( ! a.hasValue() ) {
        ... this means it has the special value 'null' or 'undefined' ...
    }
    else if( Integer::isInteger(a) ) {
        Integer::ValueType myInt = Integer::cast(a).value();
        ...
    }
    // Or:
    Object::Iterator it = obj.begin();
    Object::Iterator end = obj.end();
    for( ; it != end; ++it ) {
        Object::Entry const & e = *it;
        std::cout << e.key // UTF-8 string
                  << '='
                  << atomToJSON(e.value)
                  <<'\n';
    }
}
else { // it is an Array...
    Array ar = Array::cast(root);
    ... fetch data from the array, similar to the Object API ...
}

The various "cast" operators above don't really cast anything. They simply copy a couple internal pointers around to upgrade a base Atom object to its full-fledged concrete type. Trying to "cast" to an incompatible type will cause an exception to be thrown.

Creating JSON output (to iterators or streams):

typedef Utf8String STR;
Object root;
root.set(STR("int"),Integer(1));
root.set(STR("double"),Double(2.2));
root.set(STR("bool"),Boolean::True);
Object sub;
root.set(STR("sub"),sub);
sub.set(....);
Array ar;
sub.set(STR("array"),ar);
ar.set( 0, Integer(42) );
ar.set( 1, STR("Hi, world!") );
// Output to human-formatted JSON:
JsonFormatter fmt;
fmt.format( root, std::cout ); // also accepts an output iterator