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
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.