amazon-web-servicesamazon-dynamodbaws-sdk-cpp

Put an item in Amazon DynamoDB with AWS SDK CPP using as input the item in JSON format


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;
...

Solution

  • 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);