douxiong2738 2018-11-29 11:34
浏览 75
已采纳

如何在golang中解析json数组结构

im using the following code without success to parse json value but its inside array []

https://play.golang.org/p/5HdWeyEtvie

package main

import (
    "encoding/json"
    "fmt"
)


var input = `
[
{
    "created_at": "Thu May 31 00:00:01 +0000 2012"
},
{
    "created_at": "Thu May 31 00:00:01 +0000 2012"
}
]
`

func main() {
    var val map[string]interface{}
    if err := json.Unmarshal([]byte(input), &val); err != nil {
        panic(err)
    }
    fmt.Println(val)
}

The idea is to get the value as key and print it , like a function that get string parameter="created_at" and prints it.

  • 写回答

4条回答 默认 最新

  • dqp99585 2018-11-29 11:42
    关注

    You're unmarshaling an array to a map. That obviously won't work. you need val to be an array.

    func main() {
        var val []map[string]interface{} // <---- This must be an array to match input
        if err := json.Unmarshal([]byte(input), &val); err != nil {
            panic(err)
        }
        fmt.Println(val)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突