gpt4 book ai didi

go - 使用分片对结构进行解码将返回空值而不是空分片

转载 作者:行者123 更新时间:2023-12-01 22:08:54 24 4
gpt4 key购买 nike

如果创建没有任何标签的“照片”,则将其存储在dynamodb中,如下所示:

"tags": {
"NULL": true
},

但是,当我查询并解码记录时,我希望它会将其转换为空片,而不是我得到以下内容:
[{"photo_id":"bmpuh3jg","tags":null}]

是否可以将其转换为空 slice ?例如
[{"photo_id":"bmpuh3jg","tags":[]}]

代码示例

我的结构

type Photo struct {
Id string `json:"photo_id"`
Tags []string `json:"tags"`
}

询问

photo := &Photo{}
input := &dynamodb.QueryInput{
TableName: aws.String("local.photos"),
KeyConditionExpression: aws.String("photo_id = :photo_id"),
ExpressionAttributeValues: map[string]*dynamodb.AttributeValue{
":photo_id": {
S: aws.String(photo_id),
},
},
}
db_result, err := db.Query(input)
if err != nil {
return nil, err
} else if *db_result.Count == int64(0) {
// No item found
return nil, err
}

err = dynamodbattribute.UnmarshalListOfMaps(db_result.Items, photo)
if err != nil {
return nil, err
}

photoJSON, err := json.Marshal(photo)
if err != nil {
return nil, err
}

return photoJSON, nil

最佳答案

如果我正确理解了您的问题,要获得一个空的Tag标签({"photo_id":"bmpuh3jg","tags":[]})结果,您可以这样做:

  jsonString := `{"photo_id":"bmpuh3jg","tags":null}`

photo := &Photo{}
err := json.Unmarshal([]byte(jsonString), &photo)
if err != nil {
fmt.Println(err.Error())
}

// Here is a trick. Replace nil with an empty slice.
if photo.Tags == nil {
photo.Tags = []string{}
}
elemJSON, err := json.Marshal(photo)
if err != nil {
fmt.Println(err.Error())
}
fmt.Println(string(elemJSON)) //{"photo_id":"bmpuh3jg","tags":[]}

要了解为什么将nil slice编码为空JSON,可以查看官方文档 https://golang.org/pkg/encoding/json/

Array and slice values encode as JSON arrays, except that []byte encodes as a base64-encoded string, and a nil slice encodes as the null JSON value.



在Go Playground上检查: https://play.golang.org/p/BsxTpBlypV5

关于go - 使用分片对结构进行解码将返回空值而不是空分片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58569272/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com