Search code examples
jsongoamazon-dynamodbaws-sdkaws-sdk-go

How to save JSON response in dynamodb in GO


I want to save a JSON response in aws-dynamodb, I am using aws-dynamodb-sdk. What I'm currently doing is:

func (e *DB) saveToDynamodb(data map[string]interface{}){
params := &dynamodb.PutItemInput{
    Item: map[string]*dynamodb.AttributeValue{
        "Key": {
            M: data,
        },
    },
    TableName: aws.String("Asset_Data"),
}
resp, err := e.dynamodb.PutItem(params)

if err != nil {
    fmt.Println(err.Error())
    return
}
fmt.Println(resp)
}

But as you can see data is of map[string]interface{} type while the expected type is map[string]*AttributeValue that's why giving compilation error.

Is there any workaround to save a json response?


Solution

  • To put JSON in aws-dynamodb we first need to iterate through each attribute of JSON struct and convert it to dynamodb.AttributeValue in the following manner:

    func (e *DB) saveToDynamodb(data map[string]interface{}){
    var vv=make(map[string]*dynamodb.AttributeValue)
    
    for k,v:=range data{
        x:=(v.(string)) //assert string type
        xx:=&(x)
        vv[k]=&dynamodb.AttributeValue{S: xx,}
    }
    //s:=data["asset_id"].(string)
    params := &dynamodb.PutItemInput{
        Item: vv,
        TableName: aws.String("Asset_Data"), // Required
    }
    resp, err := e.dynamodb.PutItem(params)
    
    if err != nil {
        // Print the error, cast err to awserr.Error to get the Code and
        // Message from an error.
        fmt.Println(err.Error())
        return
    }
    
    // Pretty-print the response data.
    fmt.Println(resp)
    }