在Go语言中获取嵌套的JSON数据

huangapple go评论96阅读模式
英文:

Fetch Nested JSON data in Go

问题

我一直遇到同样的问题,即从嵌套的JSON中获取数据。

结构看起来像这样,我尝试的解决方案如下。

我收到的错误是“response.Result.Bid未定义”。我已经解码了JSON响应,所以我不太明白这里发生了什么。当我尝试追加到数组时发生错误。

如果你们有任何与这个主题相关的好资源,我会非常感激任何帮助,因为我一直遇到同样的问题。我不是来自编程背景的人,我是一名数学家。

type MarketPrices struct {
	Success bool `json:"success"`
	Result  []struct {
		Name           string      `json:"name"`
		Basecurrency   interface{} `json:"baseCurrency"`
		Quotecurrency  interface{} `json:"quoteCurrency"`
		Type           string      `json:"type"`
		Underlying     string      `json:"underlying"`
		Enabled        bool        `json:"enabled"`
		Ask            float64     `json:"ask"`
		Bid            float64     `json:"bid"`
		Last           float64     `json:"last"`
		Postonly       bool        `json:"postOnly"`
		Priceincrement float64     `json:"priceIncrement"`
		Sizeincrement  float64     `json:"sizeIncrement"`
		Restricted     bool        `json:"restricted"`
	} `json:"result"`
}

func Spot_Price() []float64 {
	res, err := http.Get("https://ftx.com/api/markets/BTC/USD")
	if err != nil {
		log.Fatal(err)
	}

	var arr []float64

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

	arr = append(arr, response.Result.Bid)

	arr = append(arr, response.Result.Ask)

	return arr
}
英文:

I keep running into the same problem, which is fetching data from nested JSON.

The struct looks like this, and my attempt at the solution is below.

The error I receive is "response.Result.Bid undefined" I have decoded the JSON response, so I do not quite understand what is going on here. The error occurs when I try to append to the array.

I'll appreciate any help, and if you guys have any good resources related to this topic that I can read about lmk because I keep running into the same problem. I do not come from a programming background, I am a mathematician by trade.

type MarketPrices struct {
	Success bool `json:"success"`
	Result  []struct {
		Name           string      `json:"name"`
		Basecurrency   interface{} `json:"baseCurrency"`
		Quotecurrency  interface{} `json:"quoteCurrency"`
		Type           string      `json:"type"`
		Underlying     string      `json:"underlying"`
		Enabled        bool        `json:"enabled"`
		Ask            float64     `json:"ask"`
		Bid            float64     `json:"bid"`
		Last           float64     `json:"last"`
		Postonly       bool        `json:"postOnly"`
		Priceincrement float64     `json:"priceIncrement"`
		Sizeincrement  float64     `json:"sizeIncrement"`
		Restricted     bool        `json:"restricted"`
	} `json:"result"`
}
func Spot_Price() []float64 {
	res, err := http.Get("https://ftx.com/api/markets/BTC/USD")
	if err != nil {
		log.Fatal(err)
	}

	var arr []float64

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

	arr = append(arr, response.Result.Bid)

	arr = append(arr, response.Result.Ask)

	return arr
}

答案1

得分: 1

在问题中提到的实际响应中,没有返回任何切片。以下是更好地建模响应的代码:

package main

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

type MarketPrices struct {
   Success bool
   Result struct {
      Ask, Bid, Last, Priceincrement, Sizeincrement  float64
      Basecurrency, Name, Quotecurrency, Type, Underlying     string
      Enabled, Postonly, Restricted     bool
   }
}

func request() (*MarketPrices, error) {
   res, err := http.Get("https://ftx.com/api/markets/BTC/USD")
   if err != nil { return nil, err }
   defer res.Body.Close()
   response := new(MarketPrices)
   json.NewDecoder(res.Body).Decode(response)
   return response, nil
}

func main() {
   price, err := request()
   if err != nil {
      panic(err)
   }
   fmt.Printf("%+v\n", price)
}
  1. https://ftx.com/api/markets/BTC/USD
英文:

With the actual response in question [1], no slice is returned. This would be a
better modeling of the response:

package main

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

type MarketPrices struct {
   Success bool
   Result struct {
      Ask, Bid, Last, Priceincrement, Sizeincrement  float64
      Basecurrency, Name, Quotecurrency, Type, Underlying     string
      Enabled, Postonly, Restricted     bool
   }
}

func request() (*MarketPrices, error) {
   res, err := http.Get("https://ftx.com/api/markets/BTC/USD")
   if err != nil { return nil, err }
   defer res.Body.Close()
   response := new(MarketPrices)
   json.NewDecoder(res.Body).Decode(response)
   return response, nil
}

func main() {
   price, err := request()
   if err != nil {
      panic(err)
   }
   fmt.Printf("%+v\n", price)
}
  1. https://ftx.com/api/markets/BTC/USD

huangapple
  • 本文由 发表于 2021年6月21日 23:24:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/68070607.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定