userver: formats::json::ValueBuilder Class Reference
Loading...
Searching...
No Matches
formats::json::ValueBuilder Class Referencefinal

#include <userver/formats/json/value_builder.hpp>

Detailed Description

Builder for JSON.

Class provides methods for building JSON. For read only access to the existing JSON values use formats::json::Value.

Example usage:

// #include <userver/formats/json.hpp>
builder["key1"] = 1;
builder["key2"]["key3"] = "val";
const formats::json::Value json = builder.ExtractValue();
ASSERT_EQ(json["key1"].As<int>(), 1);
ASSERT_EQ(json["key2"]["key3"].As<std::string>(), "val");

Customization example:

namespace my_namespace {
struct MyKeyValue {
std::string field1;
int field2;
};
// The function must be declared in the namespace of your type
// Keep external linkage in this public documentation snippet.
// NOLINTNEXTLINE(misc-use-internal-linkage)
formats::json::Value Serialize(const MyKeyValue& data, formats::serialize::To<formats::json::Value>) {
formats::json::ValueBuilder builder;
builder["field1"] = data.field1;
builder["field2"] = data.field2;
return builder.ExtractValue();
}
TEST(JsonValueBuilder, ExampleCustomization) {
const MyKeyValue object = {.field1 = "val", .field2 = 1};
formats::json::ValueBuilder builder;
builder["example"] = object;
auto json = builder.ExtractValue();
ASSERT_EQ(json["example"]["field1"].As<std::string>(), "val");
ASSERT_EQ(json["example"]["field2"].As<int>(), 1);
}
TEST(JsonValueBuilder, StringViewRemove) {
formats::json::ValueBuilder builder;
const std::string str = "ab";
builder["a"] = 1;
builder[str] = 2;
builder.Remove(std::string_view(str.data(), 1));
EXPECT_EQ(1, builder.GetSize());
const auto value = builder.ExtractValue();
EXPECT_EQ(2, value[str].As<int>());
}
TEST(JsonValueBuilder, StringViewHasMember) {
formats::json::ValueBuilder main_builder;
const std::string str = "ab";
main_builder[str] = 2;
EXPECT_EQ(false, main_builder.HasMember("a"));
EXPECT_EQ(false, main_builder.HasMember(std::string_view(str.data(), 1)));
EXPECT_EQ(true, main_builder.HasMember(std::string_view(str.data(), 2)));
}
TEST(JsonValueBuilder, StringViewEmplaceNocheck) {
formats::json::ValueBuilder main_builder;
const std::string str = "ab";
main_builder.EmplaceNocheck(std::string_view(str.data(), 1), 1);
main_builder.EmplaceNocheck(std::string_view(str.data(), 2), 2);
main_builder.EmplaceNocheck(std::string_view(std::string(1024, 'a') + 'b'), 1025);
const auto value = main_builder.ExtractValue();
EXPECT_EQ(1, value["a"].As<int>());
EXPECT_EQ(2, value["ab"].As<int>());
EXPECT_EQ(1025, value[std::string(1024, 'a') + 'b'].As<int>());
}
} // namespace my_namespace
See also
Formats (JSON, YAML, BSON, ...)
Examples
samples/config_service/main.cpp, samples/kafka_service/src/consume.cpp, samples/scylla_service/src/helpers.cpp, samples/scylla_service/src/helpers.hpp, samples/scylla_service/src/main.cpp, samples/static_service/main.cpp, samples/testsuite-support/src/metrics.cpp, samples/testsuite-support/src/now.cpp, samples/testsuite-support/src/tasks.cpp, samples/testsuite-support/src/testpoint.cpp, and samples/ydb_service/views/select-rows/post/view.cpp.

Definition at line 68 of file value_builder.hpp.

Classes

struct  IterTraits

Public Types

using iterator = Iterator<IterTraits>

Public Member Functions

 ValueBuilder ()=default
 Constructs a ValueBuilder that holds kNull.
 ValueBuilder (formats::common::Type type)
 Constructs a valueBuilder that holds default value for provided type.
 ValueBuilder (common::TransferTag, ValueBuilder &&) noexcept
 Transfers the ValueBuilder object.
 ValueBuilder (const ValueBuilder &other)
 ValueBuilder (ValueBuilder &&other)
 ValueBuilder (const formats::json::Value &other)
 ValueBuilder (formats::json::Value &&other)
template<typename T>
requires (impl::IsNativeArithmetic<T> && !meta::IsCharacter<T>)
 ValueBuilder (T value)
 Constructs a number or boolean directly.
template<typename T>
requires (impl::IsNativeArithmetic<T> && meta::IsCharacter<T>)
 ValueBuilder (T value)
 Constructs a number representing the character's code unit.
template<typename T>
requires impl::IsNativeString<T>
 ValueBuilder (const T &value)
 Constructs a string, copying its bytes into owned storage.
template<typename T>
requires (!impl::IsNativeArithmetic<T> && !impl::IsNativeString<T>)
 ValueBuilder (const T &t)
 Universal constructor using Serialize.

Native value constructors

Constructs a JSON null.

class Iterator< IterTraits, common::IteratorDirection::kForward >
class Iterator< IterTraits, common::IteratorDirection::kReverse >
 ValueBuilder (std::nullptr_t)
ValueBuilder operator[] (std::string key)
 Access member by key for modification.
ValueBuilder operator[] (std::size_t index)
 Access array member by index for modification.
template<typename Tag, utils::StrongTypedefOps Ops>
requires (utils::IsStrongTypedefLoggable(Ops))
ValueBuilder operator[] (utils::StrongTypedef< Tag, std::string, Ops > key)
 Access member by key for modification.
ValueBuilder & operator= (const ValueBuilder &other)
ValueBuilder & operator= (ValueBuilder &&other)
template<typename T>
requires (impl::IsNativeArithmetic<T> && !meta::IsCharacter<std::remove_cv_t<T>>)
ValueBuilder & operator= (T value)
 Assigns a numeric or boolean value directly, without creating a temporary builder.
template<typename T>
requires (impl::IsNativeArithmetic<T> && meta::IsCharacter<std::remove_cv_t<T>>)
ValueBuilder & operator= (T value)
 Assigns a number representing the character's code unit.
template<typename T>
requires impl::IsNativeString<T>
ValueBuilder & operator= (const T &value)
 Assigns a string, copying its bytes into owned storage. The source remains unchanged and may be modified or destroyed afterwards.
template<typename T>
requires std::is_same_v<std::remove_cvref_t<T>, formats::json::Value>
ValueBuilder & operator= (T &&value)
 Assigns an existing JSON value without constructing a temporary builder. Lvalues and const or shared rvalues are copied. Uniquely owned non-const rvalues are moved and become null. Copied sources and their aliases remain unchanged.
ValueBuilder & operator= (std::nullptr_t)
 Assigns JSON null directly, without creating a temporary builder.
void EmplaceNocheck (std::string_view key, ValueBuilder value)
 Emplaces new member w/o a check whether the key already exists.
void EmplaceNocheck (std::string_view key, const formats::json::Value &value)
 Copies an existing JSON value directly, without constructing a temporary ValueBuilder. This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
void EmplaceNocheck (std::string_view key, formats::json::Value &&value)
 Moves a uniquely owned JSON value directly, copying shared values. This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
void EmplaceNocheck (std::string_view key, std::nullptr_t)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
void EmplaceNocheck (std::string_view key, const std::string &value)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
void EmplaceNocheck (std::string_view key, std::string_view value)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
template<typename T>
requires std::is_convertible_v<const T&, std::string_view>
void EmplaceNocheck (std::string_view key, const T &value)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
template<impl::IsWrappedValue T>
void EmplaceNocheck (std::string_view key, const T &value)
 Serializes and inserts a std::optional or std::variant without constructing a temporary builder. Uses the same serialization customization as the universal constructor. This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
template<typename T>
requires (impl::IsNativeArithmetic<T> && !meta::IsCharacter<std::remove_cv_t<T>>)
void EmplaceNocheck (std::string_view key, T value)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
template<typename T>
requires (impl::IsNativeArithmetic<T> && meta::IsCharacter<std::remove_cv_t<T>>)
void EmplaceNocheck (std::string_view key, T value)
 Emplaces a number representing the character's code unit. This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
template<typename T>
void EmplaceNocheck (std::string_view key, std::initializer_list< T > initializer)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
void Remove (std::string_view key)
 Remove key from object. If key is missing nothing happens.
iterator begin ()
iterator end ()
bool IsEmpty () const
 Returns whether the array or object is empty.
bool IsNull () const noexcept
 Returns true if *this holds a Null (Type::kNull).
bool IsBool () const noexcept
 Returns true if *this is convertible to bool.
bool IsInt () const noexcept
 Returns true if *this is convertible to int.
bool IsInt64 () const noexcept
 Returns true if *this is convertible to int64_t.
bool IsUInt64 () const noexcept
 Returns true if *this is convertible to uint64_t.
bool IsDouble () const noexcept
 Returns true if *this is convertible to double.
bool IsString () const noexcept
 Returns true if *this is convertible to std::string.
bool IsArray () const noexcept
 Returns true if *this is an array (Type::kArray).
bool IsObject () const noexcept
 Returns true if *this holds a map (Type::kObject).
std::size_t GetSize () const
 Returns array size or object members count.
std::size_t GetCapacity () const
 Returns storage capacity for array elements or object members.
bool HasMember (std::string_view key) const
 Returns true if value holds a key.
std::string GetPath () const
 Returns full path to this value.
void Reserve (std::size_t capacity)
 Ensures storage capacity for array elements or object members is at least capacity without changing size.
void Resize (std::size_t size)
 Resize the array value or convert null value into an array of requested size.
void PushBack (std::nullptr_t)
 Appends a JSON null directly, without constructing a temporary ValueBuilder, converting this builder from null to an array if necessary.
void PushBack (const std::string &value)
 Appends a string directly, without constructing a temporary ValueBuilder.
void PushBack (std::string_view value)
 This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.
template<typename T>
requires std::is_convertible_v<const T&, std::string_view>
void PushBack (const T &value)
 Appends a string-like value directly, without constructing a temporary ValueBuilder.
template<impl::IsWrappedValue T>
void PushBack (const T &value)
 Serializes and appends a std::optional or std::variant without constructing a temporary builder. Uses the same serialization customization as the universal constructor.
template<typename T>
requires (std::is_arithmetic_v<T> && !meta::IsCharacter<std::remove_cv_t<T>>)
void PushBack (T value)
 Appends an arithmetic value directly, without constructing a temporary ValueBuilder.
template<typename T>
requires (std::is_arithmetic_v<T> && meta::IsCharacter<std::remove_cv_t<T>>)
void PushBack (T value)
 Appends a number representing the character's code unit.
template<typename T>
void PushBack (std::initializer_list< T > initializer)
 Appends the single element of a braced initializer. The element is forwarded to the matching PushBack overload, avoiding a temporary ValueBuilder when a direct overload is available.
void PushBack (ValueBuilder &&bld)
 Add element into the last position of array.
void PushBack (const formats::json::Value &value)
 Copy an existing JSON value into the last position of array.
void PushBack (formats::json::Value &&value)
 Move an existing JSON value into the last position of array when it is uniquely owned, otherwise copy it.
formats::json::Value ExtractValue ()
 Take out the resulting Value object. After calling this method the object is in unspecified (but valid - possibly null) state.

Member Typedef Documentation

◆ iterator

using formats::json::ValueBuilder::iterator = Iterator<IterTraits>

Definition at line 77 of file value_builder.hpp.

Constructor & Destructor Documentation

◆ ValueBuilder() [1/6]

formats::json::ValueBuilder::ValueBuilder ( common::TransferTag ,
ValueBuilder &&  )
noexcept

Transfers the ValueBuilder object.

See also
formats::common::TransferTag for the transfer semantics

◆ ValueBuilder() [2/6]

template<typename T>
requires (impl::IsNativeArithmetic<T> && !meta::IsCharacter<T>)
formats::json::ValueBuilder::ValueBuilder ( T value)
inline

Constructs a number or boolean directly.

Definition at line 99 of file value_builder.hpp.

◆ ValueBuilder() [3/6]

template<typename T>
requires (impl::IsNativeArithmetic<T> && meta::IsCharacter<T>)
formats::json::ValueBuilder::ValueBuilder ( T value)
inline

Constructs a number representing the character's code unit.

Definition at line 110 of file value_builder.hpp.

◆ ValueBuilder() [4/6]

template<typename T>
requires impl::IsNativeString<T>
formats::json::ValueBuilder::ValueBuilder ( const T & value)
inline

Constructs a string, copying its bytes into owned storage.

Definition at line 117 of file value_builder.hpp.

◆ ValueBuilder() [5/6]

template<typename T>
requires (!impl::IsNativeArithmetic<T> && !impl::IsNativeString<T>)
formats::json::ValueBuilder::ValueBuilder ( const T & t)
inline

Universal constructor using Serialize.

Definition at line 125 of file value_builder.hpp.

◆ ValueBuilder() [6/6]

formats::json::ValueBuilder::ValueBuilder ( std::nullptr_t )
inline

Definition at line 132 of file value_builder.hpp.

Member Function Documentation

◆ EmplaceNocheck() [1/6]

template<impl::IsWrappedValue T>
void formats::json::ValueBuilder::EmplaceNocheck ( std::string_view key,
const T & value )
inline

Serializes and inserts a std::optional or std::variant without constructing a temporary builder. Uses the same serialization customization as the universal constructor. This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Definition at line 238 of file value_builder.hpp.

◆ EmplaceNocheck() [2/6]

template<typename T>
requires std::is_convertible_v<const T&, std::string_view>
void formats::json::ValueBuilder::EmplaceNocheck ( std::string_view key,
const T & value )
inline

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Definition at line 226 of file value_builder.hpp.

◆ EmplaceNocheck() [3/6]

template<typename T>
void formats::json::ValueBuilder::EmplaceNocheck ( std::string_view key,
std::initializer_list< T > initializer )
inline

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Definition at line 266 of file value_builder.hpp.

◆ EmplaceNocheck() [4/6]

template<typename T>
requires (impl::IsNativeArithmetic<T> && meta::IsCharacter<std::remove_cv_t<T>>)
void formats::json::ValueBuilder::EmplaceNocheck ( std::string_view key,
T value )
inline

Emplaces a number representing the character's code unit. This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Definition at line 257 of file value_builder.hpp.

◆ EmplaceNocheck() [5/6]

template<typename T>
requires (impl::IsNativeArithmetic<T> && !meta::IsCharacter<std::remove_cv_t<T>>)
void formats::json::ValueBuilder::EmplaceNocheck ( std::string_view key,
T value )
inline

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Definition at line 245 of file value_builder.hpp.

◆ EmplaceNocheck() [6/6]

void formats::json::ValueBuilder::EmplaceNocheck ( std::string_view key,
ValueBuilder value )

Emplaces new member w/o a check whether the key already exists.

Warning
May create invalid JSON with duplicate key.
Exceptions
`TypeMismatchException`if not object or null value.

◆ ExtractValue()

formats::json::Value formats::json::ValueBuilder::ExtractValue ( )

Take out the resulting Value object. After calling this method the object is in unspecified (but valid - possibly null) state.

Exceptions
`json::Exception`if called not from the root builder.
Examples
samples/config_service/main.cpp, samples/kafka_service/src/consume.cpp, samples/mongo_service/main.cpp, samples/testsuite-support/src/metrics.cpp, samples/testsuite-support/src/now.cpp, samples/testsuite-support/src/tasks.cpp, samples/testsuite-support/src/testpoint.cpp, and samples/ydb_service/views/select-rows/post/view.cpp.

◆ GetCapacity()

std::size_t formats::json::ValueBuilder::GetCapacity ( ) const

Returns storage capacity for array elements or object members.

Exceptions
`TypeMismatchException`if not an array or an object.

◆ GetSize()

std::size_t formats::json::ValueBuilder::GetSize ( ) const

Returns array size or object members count.

Exceptions
`TypeMismatchException`if not an array or an object.

◆ HasMember()

bool formats::json::ValueBuilder::HasMember ( std::string_view key) const

Returns true if value holds a key.

Exceptions
`TypeMismatchException`if *this is not a map or null.

◆ IsEmpty()

bool formats::json::ValueBuilder::IsEmpty ( ) const

Returns whether the array or object is empty.

Exceptions
`TypeMismatchException`if not an array or an object.

◆ operator=() [1/5]

template<typename T>
requires impl::IsNativeString<T>
ValueBuilder & formats::json::ValueBuilder::operator= ( const T & value)
inline

Assigns a string, copying its bytes into owned storage. The source remains unchanged and may be modified or destroyed afterwards.

Definition at line 179 of file value_builder.hpp.

◆ operator=() [2/5]

ValueBuilder & formats::json::ValueBuilder::operator= ( std::nullptr_t )
inline

Assigns JSON null directly, without creating a temporary builder.

Definition at line 196 of file value_builder.hpp.

◆ operator=() [3/5]

template<typename T>
requires std::is_same_v<std::remove_cvref_t<T>, formats::json::Value>
ValueBuilder & formats::json::ValueBuilder::operator= ( T && value)
inline

Assigns an existing JSON value without constructing a temporary builder. Lvalues and const or shared rvalues are copied. Uniquely owned non-const rvalues are moved and become null. Copied sources and their aliases remain unchanged.

Exceptions
formats::json::MemberMissingExceptionif the source value is missing.

Definition at line 190 of file value_builder.hpp.

◆ operator=() [4/5]

template<typename T>
requires (impl::IsNativeArithmetic<T> && meta::IsCharacter<std::remove_cv_t<T>>)
ValueBuilder & formats::json::ValueBuilder::operator= ( T value)
inline

Assigns a number representing the character's code unit.

Definition at line 170 of file value_builder.hpp.

◆ operator=() [5/5]

template<typename T>
requires (impl::IsNativeArithmetic<T> && !meta::IsCharacter<std::remove_cv_t<T>>)
ValueBuilder & formats::json::ValueBuilder::operator= ( T value)
inline

Assigns a numeric or boolean value directly, without creating a temporary builder.

Definition at line 158 of file value_builder.hpp.

◆ operator[]() [1/3]

ValueBuilder formats::json::ValueBuilder::operator[] ( std::size_t index)

Access array member by index for modification.

Exceptions
`TypeMismatchException`if not an array value.
`OutOfBoundsException`if index is greater than size.

◆ operator[]() [2/3]

ValueBuilder formats::json::ValueBuilder::operator[] ( std::string key)

Access member by key for modification.

Exceptions
`TypeMismatchException`if not object or null value.

◆ operator[]() [3/3]

template<typename Tag, utils::StrongTypedefOps Ops>
requires (utils::IsStrongTypedefLoggable(Ops))
ValueBuilder formats::json::ValueBuilder::operator[] ( utils::StrongTypedef< Tag, std::string, Ops > key)
inline

Access member by key for modification.

Exceptions
`TypeMismatchException`if not object or null value.

Definition at line 147 of file value_builder.hpp.

◆ PushBack() [1/10]

void formats::json::ValueBuilder::PushBack ( const formats::json::Value & value)

Copy an existing JSON value into the last position of array.

Exceptions
`TypeMismatchException`if not an array or null.

◆ PushBack() [2/10]

void formats::json::ValueBuilder::PushBack ( const std::string & value)

Appends a string directly, without constructing a temporary ValueBuilder.

Exceptions
`TypeMismatchException`if the builder contains neither an array nor null.

◆ PushBack() [3/10]

template<impl::IsWrappedValue T>
void formats::json::ValueBuilder::PushBack ( const T & value)
inline

Serializes and appends a std::optional or std::variant without constructing a temporary builder. Uses the same serialization customization as the universal constructor.

Exceptions
formats::json::TypeMismatchExceptionif the builder is neither an array nor null.

Definition at line 362 of file value_builder.hpp.

◆ PushBack() [4/10]

template<typename T>
requires std::is_convertible_v<const T&, std::string_view>
void formats::json::ValueBuilder::PushBack ( const T & value)
inline

Appends a string-like value directly, without constructing a temporary ValueBuilder.

Exceptions
`TypeMismatchException`if the builder contains neither an array nor null.

Definition at line 350 of file value_builder.hpp.

◆ PushBack() [5/10]

void formats::json::ValueBuilder::PushBack ( formats::json::Value && value)

Move an existing JSON value into the last position of array when it is uniquely owned, otherwise copy it.

Exceptions
`TypeMismatchException`if not an array or null.

◆ PushBack() [6/10]

template<typename T>
void formats::json::ValueBuilder::PushBack ( std::initializer_list< T > initializer)
inline

Appends the single element of a braced initializer. The element is forwarded to the matching PushBack overload, avoiding a temporary ValueBuilder when a direct overload is available.

Exceptions
`Exception`if the initializer does not contain exactly one element.
`TypeMismatchException`if the builder contains neither an array nor null.

Definition at line 399 of file value_builder.hpp.

◆ PushBack() [7/10]

void formats::json::ValueBuilder::PushBack ( std::nullptr_t )

Appends a JSON null directly, without constructing a temporary ValueBuilder, converting this builder from null to an array if necessary.

Exceptions
`TypeMismatchException`if the builder contains neither an array nor null.
Examples
samples/ydb_service/views/select-rows/post/view.cpp.

◆ PushBack() [8/10]

template<typename T>
requires (std::is_arithmetic_v<T> && meta::IsCharacter<std::remove_cv_t<T>>)
void formats::json::ValueBuilder::PushBack ( T value)
inline

Appends a number representing the character's code unit.

Exceptions
`TypeMismatchException`if the builder contains neither an array nor null.

Definition at line 386 of file value_builder.hpp.

◆ PushBack() [9/10]

template<typename T>
requires (std::is_arithmetic_v<T> && !meta::IsCharacter<std::remove_cv_t<T>>)
void formats::json::ValueBuilder::PushBack ( T value)
inline

Appends an arithmetic value directly, without constructing a temporary ValueBuilder.

Exceptions
`TypeMismatchException`if the builder contains neither an array nor null.

Definition at line 370 of file value_builder.hpp.

◆ PushBack() [10/10]

void formats::json::ValueBuilder::PushBack ( ValueBuilder && bld)

Add element into the last position of array.

Exceptions
`TypeMismatchException`if not an array or null.

◆ Remove()

void formats::json::ValueBuilder::Remove ( std::string_view key)

Remove key from object. If key is missing nothing happens.

Exceptions
`TypeMismatchException`if value is not an object.

◆ Reserve()

void formats::json::ValueBuilder::Reserve ( std::size_t capacity)

Ensures storage capacity for array elements or object members is at least capacity without changing size.

Exceptions
`TypeMismatchException`if not an array or object.

◆ Resize()

void formats::json::ValueBuilder::Resize ( std::size_t size)

Resize the array value or convert null value into an array of requested size.

Exceptions
`TypeMismatchException`if not an array or null.

◆ Iterator< IterTraits, common::IteratorDirection::kForward >

friend class Iterator< IterTraits, common::IteratorDirection::kForward >
friend

Definition at line 518 of file value_builder.hpp.

◆ Iterator< IterTraits, common::IteratorDirection::kReverse >

friend class Iterator< IterTraits, common::IteratorDirection::kReverse >
friend

Definition at line 518 of file value_builder.hpp.


The documentation for this class was generated from the following file: