dongmei9020 2015-03-11 15:47
浏览 37
已采纳

Golang上的JSON-解组石墨数据

I am playing around with Golang and JSON trying to do some calculations with data extracted from Graphite API.

For simplicity, a snippet of the data sent by Graphite is:

[
{
    "target": "server1.loadavg.1min",
    "datapoints": [
        [
            0.16,
            1422770850
        ],
        [
            0.16,
            1422770880
        ],
        [
            null,
            1422771120
        ]
    ]
},
{
    "target": "server2.loadavg.1min",
    "datapoints": [
        [
            0.19,
            1422770850
        ],
        [
            null,
            1422771390
        ],
        [
            0.14,
            1422771420
        ]
    ]
}
]

I've been reading through the go json tutorial about how to use a generic interface{} for JSON arbitrary data, but I'm struggling with some aspects of the process.

I've tried to define a structure that will hold this data, read the file contents and unmarshal it to this structure:

type Graphite struct {
  Metric struct {
    Target     string      `json:"target"`
    Datapoints [][]float64 `json:"datapoints"`
  }
}

var results []Graphite
err = json.Unmarshal(d, &r)
if err != nil {
    panic(err)
}
fmt.Printf("%v
", r)

But the result is:

[{{ []}} {{ []}}]

I could do it of course with a generic interface{} but I would like to know what am I missing here.

Could you please help me?

Thank you!

  • 写回答

2条回答 默认 最新

  • dongtaotao19830418 2015-03-11 16:06
    关注

    I like to start at the simplest type and work my way out. First you need to represent your data point.

    type DataPoint []float64

    Then a metric is just a target and a series of data points.

    type Metric struct {
        Target string      `json:"target"`
        Points []DataPoint `json:"datapoints"`
    }
    

    There is no need for your Graphite struct. Your JSON is just a JSON array of Metrics.

    var results []Metric
    err := json.Unmarshal([]byte(data), &results)
    

    Here's a playground link with a complete example.

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

报告相同问题?

悬赏问题

  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan