'Go omitempty bool field- not showing false type

I have a struct

type Settings struct {
    Status             bool `json:"status,omitempty"`
    AvailableStatus        bool `json:"available_status,omitempty"`
}

I am using this struct for saving the data and displaying the data in my GOAPis

for eg if for my save data my json body is like this

{"settings":{"status":true,
"available_status":false}}

after save I fetch data data using Get-API I am getting like this

"settings": {
        "status": true
    }

only true data is displaying I need to display both data and need to set omitempty also(omit empty for saving, after that json created and using json I am checking validation)

How can I do this?

for saving the data, all fields are not required. I might be able to give json like below in my apis body.

{"settings":{"status":true,
    "available_status":false}}

or

{"settings":{"status":true}}

I want to do this also. I created json for each model and validation is checking in json .. If I not added omitempty field it will show error available_status is required.

Or any other method for setting available_status as required filed..

go


Solution 1:[1]

"omitempty" is omitting only when value is equal to zerovalue of chosen type. If you want to create custom json from struct you can make map from struct and use json.Marshal or other lib like https://github.com/tidwall/sjson

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Limmperhaven