codedor
codedor

Reputation: 83

Json field that can be string or bool into struct

I am using an API, which returns a field that is sometimes a boolean, sometimes a string.

like this:

{
   "unstable":true,
   "unstable_reason":"ANY_REASON"
}

and

{
   "unstable":false
   "unstable_reason":false
}

the struct looks like this:

        ...
        Unstable       bool   `json:"unstable"`
        UnstableReason string `json:"unstable_reason,string"`
        ...

When trying to use this, I get the following error:

panic: json: invalid use of ,string struct tag, trying to unmarshal unquoted value into string

On the other hand, when using bool for UnstableReason, an error occurs aswell.

When removing ,string, I get this error: panic: json: cannot unmarshal bool into Go struct field .data.prices.unstable_reason of type string

The field is not relevant for my purposes, so if there is a way to just let it be nil, this would also be fine.

I have no impact on the API.

Any Ideas? I am relatively new to go.

Upvotes: 2

Views: 1452

Answers (1)

Hossein Daneshvar
Hossein Daneshvar

Reputation: 169

You can use interface{} type like as:

type YourMessage struct {
    Unstable       bool        `json:"unstable"`
    UnstableReason interface{} `json:"unstable_reason"`
}

func (m YourMessage) UnstableReasonAsString() string {
    return fmt.Sprint(m.UnstableReason)
}

...
m1 := &YourMessage{}
if err := json.Unmarshal([]byte(messageJson), m1); err != nil {
    fmt.Println("Error", err)
} else {
    fmt.Println("Unstable Reason=", m1.UnstableReasonAsString())
}

Upvotes: 2

Related Questions