-
Notifications
You must be signed in to change notification settings - Fork 616
How to add a new key:value pair to an existing json object #37
Comments
The Json interface is immutable (by design), however you can build up json objects by using
Json::object mutable_json = Json::object {
{ "key1", "value1" },
{ "key2", false },
{ "key3", JSON::array { 1, 2, 3 } },
{ "key4", 666.333 }
};
mutable_json["key5"] = string {"something else"};
Json immutable_json = Json {mutable_json}; This makes sense (to me) because there is no guarantee that a Json value = 5;
value["new_key"] = 6; // doesn't compile |
Hello skabbes Many thanks for the response! The maintainer of the library may want to add your explanation to the user guide! I'm not really a JSON specialist, so I can't say what is 'legal' and what is not according to the json specification. However, from a purely practical perspective, I always think of the 'root' of the 'object' as a 'json object'. Would it really be 'Json' if it wasn't? I am passing json objects around the network, as a quick way of putting messages together, and I needed to add an 'identifier token' to each message, and I just couldn't figure out how to do that. I did mange eventually to add an 'insert' function after struggling for quite a while. Thanks |
hello skabbes, instead of this |
@maverick447 give this a try: mutable_json["key5"] = Json::object {
{ "new_key", "new_value" }
}; |
HI skabbes, |
Hi
Thanks for this library! I do find the 'user guide' rather sparse however. I can't figure out how to add a key:value pair to a json object that already exists. Say I have :
JSON j = JSON::object{
{ "key1", "value1" },
{ "key2", false },
{ "key3", JSON::array { 1, 2, 3 } },
{ "key4", 666.333 },
{ "key5", JSON::array { 1, 2, JSON::object{ { "key1", "value1" },
{ "key6", false } } } }
};
Now I want to add another key:value pair like :
j.add("key", "value"); //no add() member!
How would I do this?
furthermore, how do I change an existing value?
j["key5"] = "something else";
Any way of doing this?
Many thanks, Peter
The text was updated successfully, but these errors were encountered: