0

I am trying to process a song using API.I have tried using a specific URL in http.get and further unmarshalling the data but the only element returned in the console is {}. Any help to send me in the right direction is appreciated.

Edit: here is some code. I have this in my main file.

var data [2]Data

if err != nil {
    log.Fatal(err)
}

defer response.Body.Close()
if response.StatusCode != 200 {
    log.Fatal("Didn't get 200")
}

rawData, err := ioutil.ReadAll(response.Body)
if err != nil {
    log.Fatal(err)
}

json.Unmarshal(rawData, &data)

fmt.Println(data[0])

I have a struct created in a separate file for JSON tags/keys.

type Data struct {
    SongID          string `json:id`
    Name            string `json:name`
}
5
  • Can you show us some of your code so that we can help with specific issues within it? Thx. Commented Sep 26, 2020 at 19:00
  • @SoftwareEngineer I have edited with some of the code I have so far. Thanks! Commented Sep 26, 2020 at 19:09
  • json.Unmarshal returns an error value, you should check if it's nil and if it isn't it will tell you what the problem is which will also be the reason you're seeing {}. Commented Sep 26, 2020 at 20:21
  • ... actually in this case it probably won't say much because your target type [2]SongData does not seem to match the json structure that is returned from that url. You need to pass a type to json.Unmarshal that matches the json structurally. Commented Sep 26, 2020 at 20:26
  • play.golang.org/p/ZVwNS8bJ6cf Commented Sep 26, 2020 at 20:32

1 Answer 1

1
 type data struct {
   Error    bool `json:"error"`
   Response struct {
    Results []struct {
        ID   int    `json:"id"`
        Name string `json:"name"`
    } `json:"results"`
  } `json:"response"`
}

This should be the data structure.

  1. Use curl to request

    curl https://searchly.asuarez.dev/api/v1/song/search?query=hello

  2. use https://mholt.github.io/json-to-go/ to convert the JSON response to Golang struct.

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

1 Comment

Your code is okay, just replace the data struct. Instead of using curl just print rawData as string and convert it to struct.

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.