1

I am trying to decode some JSON retrieved via http.Get. However, when I check the structs I initialize with fmt.Println, they are always empty.

I suspect it is because my struct's structure does not agree with the returned JSON, but I am not sure how to fix it. In general, I am not exactly quite sure how the decoder works.

This is the JSON:

{
  "response":[
    {
      "list": {
        "category":"(noun)",
        "synonyms":"histrion|player|thespian|role player|performer|performing artist"
      }
    },
    {
      "list": {
        "category":"(noun)",
        "synonyms":"doer|worker|person|individual|someone|somebody|mortal|soul"
      }
    }
  ]
}

Here is what i have tried so far:

type SynonymResponse struct {
    lists []SynonymList
}

type SynonymList struct {
    category string
    synonyms string
}

var synonyms SynonymResponse;
dec := json.NewDecoder(response.Body)
err := dec.Decode(&synonyms)
if err != nil {
    log.Fatal(err)
}
fmt.Println(synonyms)

EDIT: Per @Leo's answer and @JimB's hint, there are two issues with my attempt. Below is the proper set of structs, though as Leo pointed out, this will be empty:

type SynonymResponses struct {
    resp []SynonymResponse
}

type SynonymResponse struct {
    listo SynonymList
}

type SynonymList struct {
    cat string
    syns string
} 
0

1 Answer 1

6

In order for your JSON to be picked up by the decoder, the fields in your struct must be exported.

This means you need you capitalize the field names. If you have custom naming on your fields -> json conversion, you can add json tags to your structs.

This will fix your issue:

type SynonymResponse struct {
    Lists []SynonymList `json:"response"`
}

type SynonymList struct {
    Category string `json:"category"`
    Synonyms string `json:"synonyms"`
}
Sign up to request clarification or add additional context in comments.

3 Comments

I have implemented your suggested changes, but I still have empty structs: {[{ } { }]}
@BrianVanover, your json is an object that contains a "response" field, not the SynonymResponse itself.
@JimB Thanks for the hint! I had to create one more layer of structs. I will add it in my question for future reference.

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.