我的第一个 API 返回:
{"symbol":"ARKBTC","bidPrice":"0.00037580","bidQty":"12.59000000","askPrice":"0.00037690","askQty":"328.94000000"}
我正在使用的处理代码是
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)
}
}
这给了我:
{ETHBTC {0.084704 0.084747}}
现在第二个 API 以不同的方式返回,我不知道如何重新排列它,所以我只得到我想要的字段,并按照我想要的顺序进行比较。
第二个 API 返回:
{"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"}
如您所见,第一个字段的名称是第一个 api 上的值,没有“符号”名称。那么我如何将其更改为 Symbol 的值
而且我不想要很多字段,只是相同的可比较 2(highestBid 和 lowestAsk),所以我会在结构中声明它们,但是我如何更改字段标签的名称?
最佳答案
您可以使用匿名结构并只用您需要的数据填充您的真实结构,例如:
type RealData struct {
SomeField int `json:"some_field"`
}
req := struct{DifferentField int `json:"different_field"`}{}
json.Unmarshal(data, &req)
r := RealData{req.DifferentField}
另一种方法是,正如 Vardius 所建议的那样,为您使用的每个 API 提供一个接口(interface)和两个不同的结构。
我可以想象的第三个解决方案是一个更大的结构,它具有比您实际需要更多的字段,并通过查看设置了哪些字段来区分。如果您尝试解析的 JSON 对象缺少某些字段,它们将保持为空(默认已初始化)。
关于json - 两个 Api 调用,具有不同的 JSON 响应。如何将它们输入到不同的结构中,但在 Golang 中重新排列它们几乎相同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48941393/