Parse a JSON with an empty string field

884 views Asked by At

I need to parse a JSON into Go struct. Following is the struct

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

Following is an example json:

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

The input json can have empty values for some field. Go's encoding/json library by default takes nil value for any empty string provided in JSON. I've a downstream service, which finds and replaces the replaceWith values in configurations. This is causing issues with my downstream service as it doesn't accept nil for the replaceWith parameter. I have a workaround where I'm replacing nil values by "''" but this can cause an issue where some value is replaced with ''. Is there a way for json to not parse empty string as nil and just ""

Here is a link to the code: https://play.golang.org/p/SprPz7mnWR6

2

There are 2 answers

1
blami On BEST ANSWER

In Go string type cannot hold nil value which is zero value for pointers, interfaces, maps, slices, channels and function types, representing an uninitialized value.

When unmarshalling JSON data to struct as you do in your example ReplaceWith field will indeed be an empty string ("") - which is exactly what you are asking for.

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")
    }
}
0
xs2tarunkukreja On

You can use Pointer in string and if the value is missing in JSON then it would be nil. I have done the same in past but currently I don't have code with me.