2

I am trying to parse given API response into a struct. It seems to be an array.

[
   {
      "host_name" : "hostname",
      "perf_data" : "",
      "plugin_output" : "All good",
      "state" : 0
   }
]

I cannot figure out how to create struct for it, I came up with:

type ServiceData struct {
    HostName     string `json:"host_name"`
    PerfData     string `json:"perf_data"`
    PluginOutput string `json:"plugin_output"`
    State        int    `json:"state"`
}
defer resp.Body.Close()
buf := new(bytes.Buffer)
buf.ReadFrom(resp.Body)
jsonStr := buf.String()
var servicedata ServiceData
json.Unmarshal([]byte(jsonStr), &servicedata)

But no luck.

Should I perhaps remove square brackets from the initial response? Could somebody point me in the right direction?

1
  • Just want to note that the JSON response is an array of objects containing a single object. You were trying to parse it into a single object and was failing. Creating a variable that is and array of ServiceData fixes the issue as per the answer below. Commented Jun 17, 2020 at 22:55

1 Answer 1

5

You may unmarshal JSON arrays into Go slices. So unmarshal into a value of type []ServiceData or []*ServiceData:

var servicedata []*ServiceData

A working demo:

func main() {
    var result []*ServiceData
    if err := json.Unmarshal([]byte(src), &result); err != nil {
        panic(err)
    }
    fmt.Printf("%+v", result[0])
}

const src = `[
   {
      "host_name" : "hostname",
      "perf_data" : "",
      "plugin_output" : "All good",
      "state" : 0
   }
]`

Which outputs (try it on the Go Playground):

&{HostName:hostname PerfData: PluginOutput:All good State:0}

Also note that you may unmarshal "directly from the body", no need to read the body first.

Use json.Decoder to do that:

var servicedata []*ServiceData
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
    // handle error
}

It's much shorter, easier to read and it's more efficient.

Sign up to request clarification or add additional context in comments.

1 Comment

That is exactly what I was missing. Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.