Difference between Nlohmann Json "array" and "array_t"

836 views Asked by At

How is nlohmann array_t different from Nlohmann json array? How is array_t actually used? The documentation for each is as follows.

array

Creates a JSON array value from a given initializer list. That is, given a list of values a, b, c, creates the JSON value [a, b, c]. If the initializer list is empty, the empty array [] is created.

Example,

nlohmann::json j_nonempty_init_list = json::array({1, 2, 3, 4});
std::cout << j_nonempty_init_list;
// [1,2,3,4]

array_t

To store objects in C++, a type is defined by the template parameters explained below.

  • Template Parameters
    • ArrayType container type to store arrays (e.g., std::vector or std::list)
    • AllocatorType allocator to use for arrays (e.g., std::allocator)
1

There are 1 answers

0
Botje On BEST ANSWER

json::array is a static function that converts an initializer list into a json value with internal type value_t::array.

array_t is defined as follows:

using array_t = ArrayType<basic_json, AllocatorType<basic_json>>;

where ArrayType is a template template parameter to basic_json:

template<template<typename U, typename V, typename... Args> class ObjectType =
         std::map,
         template<typename U, typename... Args> class ArrayType = std::vector,
         class StringType = std::string, class BooleanType = bool,
         class NumberIntegerType = std::int64_t,
         class NumberUnsignedType = std::uint64_t,
         class NumberFloatType = double,
         template<typename U> class AllocatorType = std::allocator,
         template<typename T, typename SFINAE = void> class JSONSerializer =
         adl_serializer,
         class BinaryType = std::vector<std::uint8_t>>
class basic_json;

and finally nlohmann::json is just the default instantiation:

using json = basic_json<>;

So, json::array_t is in the end a type alias for std::vector<json>.
You can override the types passed to basic_json if you create your own typedef over basic_json.