dongzhong2018 2015-08-10 01:29
浏览 295
已采纳

Golang解组JSON列表

I've been struggling to parse a basic array response.

My input JSON, has a list of consistent types of structures.

[
{
  "amount":"6.40000000",
  "date":"1439165701",
  "price":"350.26",
  "tid":104159
},
{
  "amount":"0.10025000",
  "date":"1439162764",
  "price":"351.03",
  "tid":104150
}
]

My struct has a nested array struct.

type TransactionResponse struct {
    Transaction []Transaction
}
type Transaction struct {
    Amount string `json:"amount"`
    Date   string `json:"date"`
    Price  string `json:"price"`
    tid    uint   `json:"tid"`
}

Function to parse the json:

func main() {
    var transactions TransactionResponse

    body, err := http.Get(url)
    err = json.Unmarshal(body, &transactions)
}

Where am I going wrong?

  • 写回答

2条回答 默认 最新

  • dtukyb8095 2015-08-10 02:02
    关注

    Decode to a slice of transactions:

    body, err := http.Get(url)
    var transactions []Transaction
    err = json.Unmarshal(body, &transactions)
    

    Also, export all of the fields:

    type Transaction struct {
      Amount string `json:"amount"`
      Date   string `json:"date"`
      Price  string `json:"price"`
      Tid    uint   `json:"tid"`
    }
    

    playground example

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 请问有会的吗,用MATLAB做
  • ¥15 phython如何实现以下功能?查找同一用户名的消费金额合并—
  • ¥15 ARIMA模型时间序列预测用pathon解决
  • ¥15 孟德尔随机化怎样画共定位分析图
  • ¥18 模拟电路问题解答有偿速度
  • ¥15 CST仿真别人的模型结果仿真结果S参数完全不对
  • ¥15 误删注册表文件致win10无法开启
  • ¥15 请问在阿里云服务器中怎么利用数据库制作网站
  • ¥60 ESP32怎么烧录自启动程序,怎么查看客户esp32板子上程序及烧录地址
  • ¥50 html2canvas超出滚动条不显示