使用空字符串字段解析JSON
我需要将JSON解析为Go结构。下面是结构使用空字符串字段解析JSON,json,go,encoding-json-go,Json,Go,Encoding Json Go,我需要将JSON解析为Go结构。下面是结构 type Replacement struct { Find string `json:"find"` ReplaceWith string `json:"replaceWith"` } 以下是一个json示例: { "find":"TestValue", "replaceWith":"" } 对于某些字段,输入js
type Replacement struct {
Find string `json:"find"`
ReplaceWith string `json:"replaceWith"`
}
以下是一个json示例:
{
"find":"TestValue",
"replaceWith":""
}
对于某些字段,输入json可以有空值。Go的encoding/json
库默认为json中提供的任何空字符串取nil
值。
我有一个下游服务,它在配置中查找并替换replacetwith
值。这导致我的下游服务出现问题,因为它不接受replaceWith
参数的nil
。我有一个变通方法,用“'
替换零
值,但这可能会导致某些值被替换为”
的问题。有没有一种方法可以让json不将空字符串解析为nil而只解析为“
下面是代码的链接:您可以在字符串中使用指针,如果JSON中缺少该值,则该值将为零。我过去也做过同样的事情,但现在我没有带代码。在Go字符串类型中不能保持
nil
值,它是指针、接口、映射、切片、通道和函数类型的零值,表示未初始化的值
当像在示例中那样将JSON数据解组到struct时,ReplaceWith
字段实际上是一个空字符串(“”
)-这正是您所要求的
type Replacement struct {
Find string `json:"find"`
ReplaceWith string `json:"replaceWith"`
}
func main() {
data := []byte(`
{
"find":"TestValue",
"replaceWith":""
}`)
var marshaledData Replacement
err := json.Unmarshal(data, &marshaledData)
if err != nil {
fmt.Println(err)
}
if marshaledData.ReplaceWith == "" {
fmt.Println("ReplaceWith equals to an empty string")
}
}
否,
encoding/json
不对空值使用nil
。显示你的代码。@BurakSerdar用代码更新了问题。你的代码正是你想要的“替换为”设置为空string@htyagi在您发布的示例中,ReplaceWith不是nil
,而是一个空字符串-正是您要求的-请参见此处:您的代码必须在问题中。链接过时了。是的,我没意识到。布拉米在上面的评论让我更清楚了。谢谢你的回答。