Boost logo

Boost :

From: Vinnie Falco (vinnie.falco_at_[hidden])
Date: 2019-11-23 19:11:00


On Sat, Nov 23, 2019 at 10:37 AM Lee Clagett via Boost
<boost_at_[hidden]> wrote:
> The bulk of cases are JSON -> specific data structure.
> The easiest implementation for JSON objects in C++ is
> storing all fields to a temporary DOM and then doing a lookup when
> mapping to a data structure.

This is an important use-case, but there are several libraries out
there which support this. The innovation in Boost.JSON is providing a
vocabulary type for the DOM that uses the discriminated union (the
`boost::json::value`). This way folks can build up layers of
abstraction using a common interface. Boost.JSON also performs well,
which is a bonus. And it is the first library to support incremental
parsing and serialization, which makes it a natural choice for network
programs.

Lets say you have this JSON:

    { "id" : 42, "name" : "John Doe", "invoices" : [ 1001, 1002, 1005, 1007 ] }

The output of the parser is a json::value which holds result. The top
level value is an object, with 3 elements. Because json::value is
SemiRegular and has a sane API, you could easily turn the parsed DOM
into this structure:

    struct customer
    {
        std::uint64_t id;
        json::string name;
        json::array invoices;

        explicit
        customer( json::value const& jv )
            : id( jv.as_object().at( "id" ).as_uint64() )
            , name( std::move( jv.as_object().at( "customer" ).as_string() ) )
            , invoices( std::move( jv.as_object().at( "invoices"
).as_array() ) )
        {
        }
    };

The customer constructor would not allocate any memory at all, instead
ownership would be transferred via noexcept move construction.

Remember that the thesis of this library is "no single JSON library
can or should satisfy all use-cases." What I have done (hopefully) is
identified a common use-case that benefits from some form of
standardization, to provide a vocabulary type for a JSON.

Thanks


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk