-1

I have a problem with unmarshaling JSON response from one of the APIs. API returns an array of simple objects. It has a structure:

  "dataFields": [
    {
      "key": "Example_key1",
      "value": "Example_value3"
    },
    {
      "key": "Example_key2",
      "value": "Example_value3"
    },
    {
      "key": "Example_key3",
      "value": "Example_value3"
    }
  ]

Generally, there are always 2 strings (possibly a null instead of a string, but this is not a problem).

Unfortunately, recently the provider has introduced a new field that looks like this:

{
  "key": "Example_key4",
  "value": false
}

Now I can not unpack it to a simple unmarshal to the structure I used before:

type DataField struct {
Value string `json:"value,omitempty"`
Key   string `json:"key,omitempty"`
}

Can you suggest to me how you can unpack something like that?

Thank you in advance

R.Slaby
  • 349
  • 2
  • 4
  • 10
  • 4
    You could change the type of your `Value` field to `interface{}` and type switch on it. "How to handle it" kind of depends on *what* you're actually doing with it. – Adrian Jun 17 '19 at 18:57
  • I collect this data and analyze it and place it in the database – R.Slaby Jun 17 '19 at 18:58
  • 1
    "collect, analyze and store" isn't a useful description. – Jonathan Hall Jun 17 '19 at 19:28
  • 1
    See [the example for json.RawMessage](https://golang.org/pkg/encoding/json/#example_RawMessage_unmarshal) for how to parse Value depending on Key. – Peter Jun 17 '19 at 19:57
  • 1
    https://play.golang.com/p/yt49VCr2TBY – mkopriva Jun 17 '19 at 20:18
  • Does the type of the value depend on the key? For example, is the value for Example_Key4 always a bool? If so, see [Decoding Generic JSON Objects to One of Many Formats](https://stackoverflow.com/questions/28033277/golang-decoding-generic-json-objects-to-one-of-many-formats). – Charlie Tumahai Jun 17 '19 at 20:52

1 Answers1

0

The problem was solved using the structure:

type DataField struct {
Value interface{} `json:"value,omitempty"`
Key   string      `json:"key,omitempty"`
}
R.Slaby
  • 349
  • 2
  • 4
  • 10