AWS SDK for Go
Developer Guide

Creating Amazon DynamoDB Table Items from a JSON File Using the AWS SDK for Go

The following example uses the DynamoDBPutItem operation in a loop to create the items defined in movie_data.json file in the Movies table in the us-west-2 region.

Create the file dynamodb_load_items.go. Add the following statements to import the Go and AWS SDK for Go packages used in the example.

import ( "encoding/json" "fmt" "io/ioutil" "os" "" "" "" "" )

Create the data structures we use to containing the information about the table item.

type ItemInfo struct { Plot string`json:"plot"` Rating float64`json:"rating"` } type Item struct { Year int`json:"year"` Title string`json:"title"` Info ItemInfo`json:"info"` }

Create a function to get the table items from the JSON file.

func getItems() []Item { raw, err := ioutil.ReadFile("./movie_data.json") if err != nil { fmt.Println(err.Error()) os.Exit(1) } var items []Item json.Unmarshal(raw, &items) return items }

Initialize the session that the SDK uses to load credentials from the shared credentials file ~/.aws/credentials, and create a new DynamoDB service client.

sess, err := session.NewSession(&aws.Config{ Region: aws.String("us-west-2")}, ) if err != nil { fmt.Println("Error creating session:") fmt.Println(err.Error()) os.Exit(1) } // Create DynamoDB client svc := dynamodb.New(sess)

Call getItems to get the items. Loop through each item, marshall that data into a map of AttributeValue objects, add the item to the Movies table, and print out the title and year of the movie added to the table.

items := getItems() // Add each item to Movies table: for _, item := range items { av, err := dynamodbattribute.MarshalMap(item) if err != nil { fmt.Println("Got error marshalling map:") fmt.Println(err.Error()) os.Exit(1) } // Create item in table Movies input := &dynamodb.PutItemInput{ Item: av, TableName: aws.String("Movies"), } _, err = svc.PutItem(input) if err != nil { fmt.Println("Got error calling PutItem:") fmt.Println(err.Error()) os.Exit(1) } fmt.Println("Successfully added '",item.Title,"' (",item.Year,") to Movies table") }

See the complete example and a sample JSON file on GitHub.