【问题标题】:Umarshalling JSON results in empty struct [duplicate]编组 JSON 导致空结构 [重复]
【发布时间】:2020-04-25 01:07:47
【问题描述】:

我有以下 JSON 结构:

dataJson := `{"data1" : [["a",1]["b",2]], "data2": ["a","b",3]}`

并且想用 Go 解组它。我正在尝试以下代码:

type myData struct {
    row    map[string][][]interface{} `json:"data1"`
    column map[string][]interface{}   `json:"data2"`
}

var arr myData

_ = json.Unmarshal([]byte(dataJson), &arr)

但我得到的是空数据:

Unmarshaled: {map[] map[]}

知道如何解析这种 JSON 结构吗?

【问题讨论】:

    标签: arrays json go slice


    【解决方案1】:

    第一个问题是必须导出结构字段(名称以大写字母开头)。详情请见Why struct fields are showing empty?

    接下来,您的输入 JSON 无效,data1 数组的元素之间缺少逗号。应该是:

    {"data1" : [["a",1],["b",2]], "data2": ["a","b",3]}
    

    第三,data1data2 是 JSON 数组,所以你必须在 Go 中使用切片而不是映射。

    类似这样的:

    type myData struct {
        Row    [][]interface{} `json:"data1"`
        Column []interface{}   `json:"data2"`
    }
    

    json.Unmarshal() 返回错误,在 Go 中永远不要忽略错误。您至少可以打印它们,这样您就会知道有些地方不对:

    dataJson := `{"data1" : [["a",1],["b",2]], "data2": ["a","b",3]}`
    
    var arr myData
    if err := json.Unmarshal([]byte(dataJson), &arr); err != nil {
        log.Println(err)
    }
    log.Printf("Unmarshaled: %v", arr)
    

    这个输出(在Go Playground上试试):

    2009/11/10 23:00:00 Unmarshaled: {[[a 1] [b 2]] [a b 3]}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-03-05
      • 1970-01-01
      • 1970-01-01
      • 2019-06-08
      • 2021-11-12
      • 1970-01-01
      • 2020-02-27
      • 1970-01-01
      相关资源
      最近更新 更多