Convert DynamoDB JSON to AttributeValue, Go Object or Json
Asked Answered
P

1

6

I am trying to convert simple DynamoDB Object string:

{
  "Item": {
    "Id": {
      "S": "db31"
    },
    "CreateTime": {
      "N": "1647882237618915000"
    }
}

to either dynamodb.AttributeValue and then map to a go object (go type structure) or convert to a simple JSON go object.

I think, there are similar answers (1, 2, 3) in Java, but I didn't find a similar implementation in Golang.

Prue answered 1/12, 2022 at 1:21 Comment(0)
M
2

You could create a struct type and use json.Unmarshal to unmarshal the JSON string like this:

package main

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

type Record struct {
    Item struct {
        Id struct {
            S string
        }
        CreateTime struct {
            N string
        }
    }
}

func main() {

    str := `{
  "Item": {
    "Id": {
      "S": "db31"
    },
    "CreateTime": {
      "N": "1647882237618915000"
    }
  }
}`

    var record Record
    if err := json.Unmarshal([]byte(str), &record); err != nil {
        fmt.Fprintf(os.Stderr, "unmarshal failed: %v", err)
        os.Exit(1)
    }

    fmt.Printf("%s %s", record.Item.Id.S, record.Item.CreateTime.N)
}


If you want a different approach, and want to transform the result into a structure that is different than the JSON, you could use a library like gjson.

Here is an example "flattening" the result into a simpler struct:

package main

import (
    "fmt"
    "github.com/tidwall/gjson"
)

type Record struct {
    Id         string
    CreateTime string
}

func main() {

    str := `{
  "Item": {
    "Id": {
      "S": "db31"
    },
    "CreateTime": {
      "N": "1647882237618915000"
    }
  }
}`

    values := gjson.GetMany(str, "Item.Id.S", "Item.CreateTime.N")

    record := Record{
        Id:         values[0].Str,
        CreateTime: values[1].Str,
    }

    fmt.Printf("%s %s", record.Id, record.CreateTime)
}
Mackler answered 1/12, 2022 at 2:18 Comment(4)
yeah, this is what I am doing, but accessing things, starts to look like: item.M["third"].B, and if the structs are more nested because the stored objects are more complex, it becomes very tedious to read and understand. I was hoping there would be a function in aws sdk that might abstract all those DynamoDB data types and Unmarshal to something that is more JSON/GO object like. Also, someone who isn't familiar with Dyn types and JSONL object representation will definitely be confused.Prue
Also, what about items/objects of unknown schema/structure? Is there code in the AWS SDK that automatically maps DynamoDB types to JSON/GO types?Prue
Check my edit. You could use a library like gjson to transform the data into a cleaner struct if that is what you're looking for.Mackler
I was hoping this would be more auto-magicated in Go like it is in Java, but it will do. Thank you!Prue

© 2022 - 2024 — McMap. All rights reserved.