Adds a json value.
#include <jsoncons_ext/jsonpointer/jsonpointer.hpp>
template<class Json>
jsonpointer_errc insert(Json& target, const typename Json::string_view_type& path, const Json& value); Inserts a value into the target at the specified path, if the path doesn't specify an object member that already has the same key.
-
If
pathspecifies an array index, a new value is inserted into the array at the specified index. -
If
pathspecifies an object member that does not already exist, a new member is added to the object.
On success, a value-initialized jsonpointer_errc.
On error, a jsonpointer_errc error code
#include <jsoncons/json.hpp>
#include <jsoncons_ext/jsonpointer/jsonpointer.hpp>
using namespace jsoncons;
int main()
{
json target = json::parse(R"(
{ "foo": "bar"}
)");
auto ec = jsonpointer::insert(target, "/baz", json("qux"));
if (ec == jsonpointer::jsonpointer_errc())
{
std::cout << target << std::endl;
}
else
{
std::cout << make_error_code(ec).message() << std::endl;
}
}Output:
{"baz":"qux","foo":"bar"}#include <jsoncons/json.hpp>
#include <jsoncons_ext/jsonpointer/jsonpointer.hpp>
using namespace jsoncons;
int main()
{
json target = json::parse(R"(
{ "foo": [ "bar", "baz" ] }
)");
auto ec = jsonpointer::insert(target, "/foo/1", json("qux"));
if (ec == jsonpointer::jsonpointer_errc())
{
std::cout << target << std::endl;
}
else
{
std::cout << make_error_code(ec).message() << std::endl;
}
}Output:
{"foo":["bar","qux","baz"]}#include <jsoncons/json.hpp>
#include <jsoncons_ext/jsonpointer/jsonpointer.hpp>
using namespace jsoncons;
int main()
{
json target = json::parse(R"(
{ "foo": [ "bar", "baz" ] }
)");
auto ec = jsonpointer::insert(target, "/foo/-", json("qux"));
if (ec == jsonpointer::jsonpointer_errc())
{
std::cout << target << std::endl;
}
else
{
std::cout << make_error_code(ec).message() << std::endl;
}
}Output:
{"foo":["bar","baz","qux"]}#include <jsoncons/json.hpp>
#include <jsoncons_ext/jsonpointer/jsonpointer.hpp>
using namespace jsoncons;
int main()
{
json target = json::parse(R"(
{ "foo": "bar", "baz" : "abc"}
)");
auto ec = jsonpointer::insert(target, "/baz", json("qux"));
if (ec == jsonpointer::jsonpointer_errc())
{
std::cout << target << std::endl;
}
else
{
std::cout << make_error_code(ec).message() << std::endl;
}
}Output:
Key already exists
#include <jsoncons/json.hpp>
#include <jsoncons_ext/jsonpointer/jsonpointer.hpp>
using namespace jsoncons;
int main()
{
json target = json::parse(R"(
{ "foo": [ "bar", "baz" ] }
)");
auto ec = jsonpointer::insert(target, "/foo/3", json("qux"));
if (ec == jsonpointer::jsonpointer_errc())
{
std::cout << target << std::endl;
}
else
{
std::cout << make_error_code(ec).message() << std::endl;
}
}Output:
Index exceeds array size