用分片对结构进行解组将返回空值而不是空分片 [英] Unmarshal to struct with slice returns null value instead of empty slice
问题描述
如果我创建没有任何标签的照片",则将其存储为dynamodb中的
If I create a "photo" without any tags it is stored in dynamodb as
"tags": {
"NULL": true
},
但是当我查询并解组记录时,我希望它会将其转换成一个空片,而不是我得到这个:
But when I query and unmarshal the record I would expect that it converts this into an empty slice instead I get this:
[{"photo_id":"bmpuh3jg","tags":null}]
是否可以将其转换为空切片?例如
Is it possible to have it convert it into an empty slice instead? e.g.
[{"photo_id":"bmpuh3jg","tags":[]}]
代码示例
我的结构
CODE EXAMPLE
My struct
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
推荐答案
如果我正确理解了您的问题,要获得一个空白的标签({"photo_id":"bmpuh3jg","tags":[]}
)结果,您可以这样做:
If I understand your question correctly, to achieve a result with an empty slice for Tags ({"photo_id":"bmpuh3jg","tags":[]}
), you can do it like this:
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":[]}
要了解为什么将零片段编码为空JSON,您可以查看官方文档 https://golang.org/pkg/encoding/json/
To understand, why a nil slice encodes as the null JSON, you can check official documentation https://golang.org/pkg/encoding/json/
数组和切片值编码为JSON数组,除了[] byte 编码为base64编码的字符串,而nil slice编码为 空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
Check on Go Playground: https://play.golang.org/p/BsxTpBlypV5
这篇关于用分片对结构进行解组将返回空值而不是空分片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!