danielaparker / jsoncons

A C++, header-only library for constructing JSON and JSON-like data formats, with JSON Pointer, JSON Patch, JSON Schema, JSONPath, JMESPath, CSV, MessagePack, CBOR, BSON, UBJSON
https://danielaparker.github.io/jsoncons
Other
699 stars 158 forks source link

push_back method for empty basic_json #427

Closed wang-sy closed 1 year ago

wang-sy commented 1 year ago

Problem Code

int main() {
  jsoncons::json obj;

  obj["not_exist_key"].push_back("array_item");

  cout << obj << endl;

  return 0;
}

now

we got

libc++abi: terminating with uncaught exception of type jsoncons::json_runtime_error<std::domain_error, void>: Attempting to insert into a value that is not an array

cause when key not exist in parent, evaluate_with_default method only creates a new object.

expect

The default operation object of thepush_back method is array. When the key operated by the user does not exist, we should help user to complete the creation of the array object by default.

expect result

{"not_exist_key":["array_item"]}

danielaparker commented 1 year ago

While not as terse, I'll think you'll need to write that as

    if (!obj.contains("not_exist_key"))
    {
        obj["not_exist_key"] = jsoncons::json(jsoncons::json_array_arg);
    }
    obj["not_exist_key"].push_back("array_item");

or (more efficiently) as


    auto pair = obj.try_emplace("not_exist_key", jsoncons::json_array_arg); // inserts array if not exists
    pair.first->value().push_back("array_item");

We don't support changing the json_type as a result of calling a member function.