Create an object from path #468
-
Hi, @danielaparker! Thank you for creating such a great library. I've encountered a minor problem related to a specific scenario. Let's assume we have the following pseudocode: jsoncons::json doc = '{"a": 5}';
std::string path = "$.b"; // potentially it may be any possible path
jsoncons::json new_obj = create_object_from_path(path); // {"b": "str"}
jsoncons::mergepatch::apply_merge_patch(value, new_obj); // {"a": 5, "b": "str"} Currently, I'm considering creating a path parser or normalizer to obtain a vector of strings, or perhaps translating the path into JSONPointer notation and utilizing the add method. I'm curious if there's a more elegant solution for implementing create_object_from_path that may already exist. Thank you in advance! |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 1 reply
-
Apologies for the late response. If your paths were represented by JSONPointers, you may be able to use the jsonpointer::replace function with the
Output:
|
Beta Was this translation helpful? Give feedback.
-
In version 0.172.0, you'll be able to write (currently supported on master) #include <jsoncons/json.hpp>
#include <jsoncons_ext/jsonpointer/jsonpointer.hpp>
#include <jsoncons_ext/jsonpath/jsonpath.hpp>
int main()
{
try
{
std::string str = R"($['b']['c'])"; // or "$.b.c"
jsoncons::jsonpath::json_location location = jsoncons::jsonpath::json_location::parse(str);
jsoncons::jsonpointer::json_pointer ptr{};
for (const auto& element : location)
{
if (element.has_name())
ptr /= element.name();
else
{
ptr /= element.index();
}
}
std::cout << "JSONPointer: " << ptr << std::endl;
jsoncons::json doc = jsoncons::json::parse(R"({"a": 5})");
jsoncons::jsonpointer::replace(doc, ptr, "str", true);
std::cout << pretty_print(doc) << std::endl;
}
catch (const std::exception& e)
{
std::cerr << e.what() << std::endl;
}
} Output:
|
Beta Was this translation helpful? Give feedback.
In version 0.172.0, you'll be able to write (currently supported on master)