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条)

报告相同问题?

悬赏问题

  • ¥15 CST仿真别人的模型结果仿真结果S参数完全不对
  • ¥15 请问在阿里云服务器中怎么利用数据库制作网站
  • ¥60 ESP32怎么烧录自启动程序
  • ¥50 html2canvas超出滚动条不显示
  • ¥15 java业务性能问题求解(sql,业务设计相关)
  • ¥15 52810 尾椎c三个a 写蓝牙地址
  • ¥15 elmos524.33 eeprom的读写问题
  • ¥15 用ADS设计一款的射频功率放大器
  • ¥15 怎么求交点连线的理论解?
  • ¥20 软件开发方法学习来了