英文:
Convert DynamoDB JSON to AttributeValue, Go Object or Json
问题
我正在尝试将简单的DynamoDB对象字符串转换为dynamodb.AttributeValue
,然后映射到一个Go对象(Go类型结构),或者转换为一个简单的JSON Go对象。
我认为,在Java中有类似的答案(1,2,3),但我没有在Golang中找到类似的实现。
英文:
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.
答案1
得分: 2
你可以创建一个结构体类型,并使用json.Unmarshal
来解析JSON字符串,代码如下:
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)
}
如果你想采用不同的方法,并将结果转换为与JSON不同的结构体,你可以使用类似gjson的库。下面是一个将结果“展平”为更简单的结构体的示例:
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)
}
希望对你有帮助!
英文:
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)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论