0

Is there any easy way to put an item in Amazon DynamoDB with AWS SDK CPP using as input the item in JSON format? Something like

Aws::DynamoDB::Model::PutItemRequest request;
request.SetTableName(table);
request.FunctionThatSetsAllAttributesParsingAJsonString(json_string);

Or is it always necessary to set each attribute and its type?

Aws::DynamoDB::Model::PutItemRequest request;
request.SetTableName(table);
Aws::DynamoDB::Model::AttributeValue val1;
val1.SetS(str);
request.AddItem(key, val1);
Aws::DynamoDB::Model::AttributeValue val2;
...
Medical physicist
  • 2,510
  • 4
  • 34
  • 51
  • I do not believe there is an interface that accepts a JSON string but you could iterate over the keys of the JSON, populate an AttributeValue, and add that to the PutItemRequest in a somewhat generic fashion. Presumably you really want/need to use C++ but, if not, there are much easier ways to do this in other languages. – jarmod Apr 15 '21 at 15:17

1 Answers1

0

If the JSON object follows Amazon DynamoDB JSON format, you can easily convert it into an Aws::Map<Aws::String, Aws::DynamoDB::Model::AttributeValue> object. For instance, for a Jsoncpp Json::Value object:

Aws::Map<Aws::String, Aws::DynamoDB::Model::AttributeValue> json2atts(const Json::Value& json) {
    try {
        Aws::Map<Aws::String, Aws::DynamoDB::Model::AttributeValue> amap;
        Aws::Utils::Json::JsonValue jval(Json::FastWriter().write(json));
        if (!jval.WasParseSuccessful()) {
            throw exception("Failed to parse input JSON");
        };
        Aws::Utils::Json::JsonView jview = jval.View();
        Aws::Map<Aws::String, Aws::Utils::Json::JsonView> jmap = jview.GetAllObjects();
        for(auto& i : jmap) {
            amap[i.first] = i.second.AsObject();
        };
        return amap;
    }
    catch (std::exception &e) { 
       ...
    };
};

Then, to put the Aws::Map<Aws::String, Aws::DynamoDB::Model::AttributeValue> object:

Aws::DynamoDB::Model::PutItemRequest request;
request.SetTableName(table);
request.SetItem(amap);
Medical physicist
  • 2,510
  • 4
  • 34
  • 51