Reputation: 757
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
Upvotes: -2
Views: 1141
Reputation: 7411
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")
}
}
Upvotes: 1
Reputation: 462
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.
Upvotes: 0