dqcj32855 2014-03-06 00:12
浏览 69
已采纳

解组未命名对象的未命名JSON数组

The JSON I am trying to unmarshal with Go is unnamed array of unnamed objects:

[
{
    "date": 1394062029,
    "price": 654.964,
    "amount": 5.61567,
    "tid": 31862774,
    "price_currency": "USD",
    "item": "BTC",
    "trade_type": "ask"
},
{
    "date": 1394062029,
    "price": 654.964,
    "amount": 0.3,
    "tid": 31862773,
    "price_currency": "USD",
    "item": "BTC",
    "trade_type": "ask"
},
{
    "date": 1394062028,
    "price": 654.964,
    "amount": 0.0193335,
    "tid": 31862772,
    "price_currency": "USD",
    "item": "BTC",
    "trade_type": "bid"
}
]

I can successfully unmarshal the object and print the complete tradesResult array as %#v, but when I try to access element of the array I get the following error.

prog.go:41: invalid operation: tradeResult[0] (index of type *TradesResult)

Here is example code you can run to try the problem:

// You can edit this code!
// Click here and start typing.
package main

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

type TradesResultData struct {
    Date     float64 `json:"date"`
    Price    float64 `json:"price"`
    Amount   float64 `json:"amount"`
    Trade    float64 `json:"tid"`
    Currency string  `json:"price_currency"`
    Item     string  `json:"item"`
    Type     string  `json:"trade_type"`
}

type TradesResult []TradesResultData

func main() {
    resp, err := http.Get("https://btc-e.com/api/2/btc_usd/trades")
    if err != nil {
        fmt.Printf("%s
", err)
    }
    json_response, err := ioutil.ReadAll(resp.Body)
    if err != nil {
        fmt.Printf("%s
", err)
    }
    resp.Body.Close()
    fmt.Printf("JSON:
%s
", json_response)
    tradeResult := new(TradesResult)
    err = json.Unmarshal(json_response, &tradeResult)
    if err != nil {
        fmt.Printf("%s
", err)
    }
    // Printing trade result first element Amount
    fmt.Printf("Element 0 Amount: %v
", tradeResult[0].Amount)
}
  • 写回答

1条回答 默认 最新

      报告相同问题?

      相关推荐 更多相似问题

      悬赏问题

      • ¥15 香农解码的代码问题,无法输出解码结果
      • ¥15 内网同一网段设备和wifi隔离
      • ¥15 Python操作注册表
      • ¥45 入门级别的一段VUE前端拍照像后端发送请求的代码,帮排错
      • ¥15 anaconda打开spyder后一直闪退,不知道怎么办
      • ¥15 解决迷宫问题中无法运行的问题
      • ¥15 关于aspnetcore中使用mqttnet库的entire
      • ¥15 关于#python#的问题,请各位专家解答!
      • ¥100 关于远控软件的两个问题
      • ¥15 基于STM32的AD8232心电采集装置设计