Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/go/7.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用空字符串字段解析JSON_Json_Go_Encoding Json Go - Fatal编程技术网

使用空字符串字段解析JSON

使用空字符串字段解析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

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

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
,而是一个空字符串-正是您要求的-请参见此处:您的代码必须在问题中。链接过时了。是的,我没意识到。布拉米在上面的评论让我更清楚了。谢谢你的回答。