my first API returns:
{"symbol":"ARKBTC","bidPrice":"0.00037580","bidQty":"12.59000000","askPrice":"0.00037690","askQty":"328.94000000"}
And the code to deal with i am using is
type Tckrstr struct {
Symbol string `json:"symbol"`
data
}
type data struct {
BidPrice float64 `json:"bidPrice,string,omitempty"`
AskPrice float64 `json:"askPrice,string,omitempty"`
}
func BinTckr() []Tckrstr {
raw, err := http.Get("https://api.binance.com/api/v3/ticker/bookTicker")
data, _ := ioutil.ReadAll(raw.Body)
if err != nil {
fmt.Println(err.Error())
os.Exit(1)
}
var m []Tckrstr
_ = json.Unmarshal(data, &m)
return m
}
func main() {
bintckr := BinTckr()
//do something with bintckr
for _, p := range bintckr {
fmt.Println(p)
}
}
This gives me:
{ETHBTC {0.084704 0.084747}}
now the second API returns way differently and i dont know how to rearrange it so i get just the fields i want, and in the order i want so they are comparable.
second API returns:
{"BTC_BCN":{"id":7,"last":"0.00000052","lowestAsk":"0.00000052","highestBid":"0.00000051","percentChange":"0.00000000","baseVolume":"36.50980204","quoteVolume":"69581654.14097802","isFrozen":"0","high24hr":"0.00000054","low24hr":"0.00000051"}
as you can see with this one, the Name of the first field is the value on the first api, and there is no "symbol" name. so how would i change it to be a Value for Symbol
as well as i wouldnt want alot of the fields, just the same comparable 2 (highestBid and lowestAsk), so i would declare them in the struct, but then how do i change the name a field label?
You can use anonymous structs and fill your real struct only with the data you need, for example:
type RealData struct {
SomeField int `json:"some_field"`
}
req := struct{DifferentField int `json:"different_field"`}{}
json.Unmarshal(data, &req)
r := RealData{req.DifferentField}
Another way is, as Vardius suggested, an interface and two different structs for each of the APIs you use.
The third solution I can imagine is a larger struct that has more fields than you actually need and distinguish between by looking which fields are set. If the JSON object you're trying to parse is missing some fields, they will stay empty (default initialized).