首页 > 解决方案 > 在 Golang 中初始化和插入嵌套的 JSON 数据?

问题描述

在过去的 3 个小时里,我一直在努力尝试让它工作,所以希望你们能够帮助我解决这个问题。

我正在尝试在 Go 中初始化嵌套的 JSON 结构并将数据插入其中。这是我要处理的 JSON 的结构:

{
  "top": {
    "item1": {
      "foo": "bar"
    },
    "item2": "This is item2",
    "item3": "This is item3",
    "item4": {
      "foo2": "bar2"
    }
  }
}

这就是我在 Go 中设置它的方式——

package main

import (
"fmt"
)

func main() {

data := make(map[string]map[string]map[string]string) // init top level map
data["top"] = make(map[string]map[string]string)
data["top"]["item1"] = make(map[string]string)
data["top"]["item4"] = make(map[string]string)


data["top"]["item1"]["foo"] = "bar"
data["top"]["item4"]["foo2"] = "bar2"
data["top"]["item2"] = "This is item2"


fmt.Println(data)
}

但是,如果我运行它,我会收到此错误:

不能在赋值中使用“This is item2”(类型字符串)作为类型 map[string]string

我确定我让这变得过于复杂,那么表达这一点的更有效方式是什么?

标签: jsongo

解决方案


使用嵌套映射可能会有点混乱,因此使用结构可能有助于使您的数据结构更易于管理。

考虑使用json-to-go 之类的工具来帮助您为 JSON 数据构建适当的对象。

注意: 这不会每次都提供完美的结构 - 事实上,当它无法识别正确的类型时,这个工具通常会默认使用接口类型(这并不理想),因此您可能需要自定义输出,但总体而言,它将为您提供一个良好的起点。

操场上的工作示例


推荐阅读