Adds a json
value.
#include <jsoncons_ext/jsonpointer/jsonpointer.hpp>
template<class J>
void insert(J& target, const typename J::string_view_type& path, const J& value); // (1)
template<class J>
void insert(J& target, const typename J::string_view_type& path, const J& value, std::error_code& ec); // (2)
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
path
specifies an array index, a new value is inserted into the array at the specified index. -
If
path
specifies an object member that does not already exist, a new member is added to the object.
None
(1) Throws a jsonpointer_error if insert
fails.
(2) Sets the std::error_code&
to the jsonpointer_error_category if insert
fails.
#include <jsoncons/json.hpp>
#include <jsoncons_ext/jsonpointer/jsonpointer.hpp>
using namespace jsoncons;
int main()
{
json target = json::parse(R"(
{ "foo": "bar"}
)");
std::error_code ec;
jsonpointer::insert(target, "/baz", json("qux"), ec);
if (ec)
{
std::cout << ec.message() << std::endl;
}
else
{
std::cout << target << 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" ] }
)");
std::error_code ec;
jsonpointer::insert(target, "/foo/1", json("qux"), ec);
if (ec)
{
std::cout << ec.message() << std::endl;
}
else
{
std::cout << target << 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" ] }
)");
std::error_code ec;
jsonpointer::insert(target, "/foo/-", json("qux"), ec);
if (ec)
{
std::cout << ec.message() << std::endl;
}
else
{
std::cout << target << 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"}
)");
std::error_code ec;
jsonpointer::insert(target, "/baz", json("qux"), ec);
if (ec)
{
std::cout << ec.message() << std::endl;
}
else
{
std::cout << target << 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" ] }
)");
std::error_code ec;
jsonpointer::insert(target, "/foo/3", json("qux"), ec);
if (ec)
{
std::cout << ec.message() << std::endl;
}
else
{
std::cout << target << std::endl;
}
}
Output:
Index exceeds array size