-2

I do not know how to select specific JSON data.

How can I change this code so that I have just the id, and none of the other response data?

I read online, and apparently I need to use a struct? I am unsure of how to approach this problem.

package main 

import(
    "fmt"
    "io"
    "log"
    "net/http"
)

func get_single_product() {

    res, err := http.Get("https://api.pro.coinbase.com/products/UNI-USD")

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

    data, err := io.ReadAll(res.Body)
    res.Body.Close()

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

    fmt.Printf("%s", data)

}

func main() {

    // CALL GET PRODUCTS FUNCTION
    get_single_product()
}

This Returns...

{
"id":"UNIUSD",
"base_currency":"UNI",
"quote_currency":"USD",
"base_min_size":"0.1",
"base_max_size":"200000",
"quote_increment":"0.0001",
"base_increment":"0.000001",
"display_name":"UNI/USD",
"min_market_funds":"1.0",
"max_market_funds":"100000",
"margin_enabled":false,
"post_only":false,
"limit_only":false,
"cancel_only":false,
"trading_disabled":false,
"status":"online",
"status_message":""
}

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189

1 Answers1

1

You can use the encoding/json package to decode your json data to an object. Just define the fields you are interested in the object and it will only read out those. Then create a decoder with json.NewDecoder().

package main

import (
    "encoding/json"
    "fmt"
    "log"
    "net/http"
)

type Response struct {
    ID string `json:"id"`
}

func main() {
    res, err := http.Get("https://api.pro.coinbase.com/products/UNI-USD")
    if err != nil {
        log.Fatal(err)
    }

    var response Response
    json.NewDecoder(res.Body).Decode(&response)

    fmt.Println(response.ID)
}

// Output
UNI-USD

See also this question: How to get JSON response from http.Get

Peter
  • 29,454
  • 5
  • 48
  • 60
schilli
  • 1,700
  • 1
  • 9
  • 17