How to append new key-value pairs in an existing web::json::value object using Casablanca?

1.5k views Asked by At

I am using Casablanca C++ REST library to work with JSON data. This is the code I am using to create a new JSON object from scratch, and add key-values pairs.

web::json::value temp;

// 1 - to add literal key-value pairs
temp[L"key1"] = web::json::value::string(U("value1"));

// 2 - to add key-value pairs of variables whose values I don't know, and are passed as std::string
temp[utility::conversions::to_string_t(key2)] = web::json::value::string(utility::conversions::to_string_t(value2)); 

This works perfectly fine and I can use it on new objects and add as many key-value pairs as I need.

My problem is that I need to append these keys to an existing web::json::value object, instead of creating a new one from scratch. I do not know the structure of the existing object, so the code will have to either update the value corresponding to the key (if it exists), or add a new key-value pair (if it doesn't already exist).

When I try the same code, except that I assign temp to some existing value using this line:

web::json::value temp = m_value; //m_value is an existing object

I get a json::exception as soon as I try to access temp with the operator [] (using either of the two methods I use above).

How can I achieve what I need? I have searched on SO but I haven't found Casablanca-specific answers to my question.

1

There are 1 answers

0
Kajal On

I have found a workaround that works for me, but I am not convinced that this is a good approach. Awaiting other answers, but this may help those who reach this question.

The workaround is to create a new object and add the new key-value pair, followed by iterating over the older object and adding all the keys one by one. This probably has quite a bad performance.

web::json::value temp;
temp[key] = web::json::value::string(newvalue); // key and newvalue are of type utility::string_t

// m_value is the web::json::value which currently holds data
for (auto iter = m_value.as_object().cbegin(); iter != m_value.as_object().cend(); ++iter)
{
    const std::string jsonKey = utility::conversions::to_utf8string(iter->first);
    const web::json::value &jsonVal = iter->second;
    temp[utility::conversions::to_string_t(jsonKey)] = jsonVal;
}

m_value = temp;