解析带有空字符串字段的 JSON

Parse a JSON with an empty string field

我需要将 JSON 解析为 Go 结构。以下是结构

type Replacement struct {
Find        string `json:"find"`
ReplaceWith string `json:"replaceWith"`
}

下面是一个例子json:

{
"find":"TestValue",
"replaceWith":""
}

输入 json 的某些字段可以有空值。 Go 的 encoding/json 库默认为 JSON 中提供的任何空字符串采用 nil 值。 我有一个下游服务,它查找并替换配置中的 replaceWith 值。这导致我的下游服务出现问题,因为它不接受 nil 作为 replaceWith 参数。我有一个解决方法,我将 nil 值替换为 "''",但这可能会导致某些值被替换为 '' 的问题。有没有办法 json 到 not 将空字符串解析为 nil 而只是 ""

这里是一个link代码:https://play.golang.org/p/SprPz7mnWR6

您可以在字符串中使用指针,如果 JSON 中缺少该值,那么它将为 nil。我过去也做过同样的事情,但目前我没有代码。

在 Go 中,字符串类型不能保存 nil 值,该值对于指针、接口、映射、切片、通道和函数类型来说是零值,表示未初始化的值。

当像您在示例中所做的那样将 JSON 数据解组为结构时,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")
    }
}