将复杂的JSON结构进行Intial iNial置于Golang的地图中



我需要向功能提供map[string]interface{}。背后的JSON是:


{
   "update": {
     "comment": [
         {
            "add": {
               "body": "this is a body"
            }
         }
      ]
   }
}

我完全被卡住了。我尝试使用嵌套结构,带有地图,两者的混合在一起,我只是看不到这个简单的东西的解决方案。

我的最后一次尝试是:

    // Prepare the data
    var data = make(map[string]interface{})
    var comments []map[string]map[string]string
    var comment = make(map[string]map[string]string)
    comment["add"] = map[string]string{
        "body": "Test",
    }
    comments = append(comments, comment)
    data["update"]["comment"] = comments

通常人们使用 interface{}Unmarshal()

查看一些示例

  • 在这里,"在Go中解析深深嵌套的Json"
  • 在这里,对于"在Golang中删除嵌套的JSON对象"
  • 在这里,对于" Golang将JSON放入接口"

希望这会有所帮助!:(

您可以使用以下格式创建和初始化JSON对象。

import (
   "fmt",
   "encoding/json"
)

type Object struct {
     Update Update `json:"update"`
}
type Update struct {
    Comments []Comment `json:"comments"`
}
type Comment struct {
    Add Add `json:"add"`
}
type Add struct {
    Body Body `json:"body"`
}
type Body string
func main() {
    obj := make(map[string]Object)
    obj["buzz"] = Object{
        Update: Update{
            Comments: []Comment{
                Comment{
                    Add: Add{
                         Body: "foo",
                    },
                },
            },
        },
    }
    fmt.Printf("%+vn", obj)
    obj2B, _ := json.Marshal(obj["buzz"])
    fmt.Println(string(obj2B))
}

初始化的对象OBJ将为

map[buzz:{Update:{Comments:[{Add:{Body:foo}}]}}]

尝试此处可用此代码。有关更多详细信息,请参考本文

我成功了,我觉得很丑。

        // Prepare the data
        var data = make(map[string]interface{})
        var comments []map[string]map[string]string
        var comment = make(map[string]map[string]string)
        comment["add"] = map[string]string{
            "body": "Test",
        }
        comments = append(comments, comment)
        var update = make(map[string]interface{})
        update["comment"] = comments
        data["update"] = update

可能迟到了3年,但我本人也偶然发现了这个问题,显然您也可以做这样的事情:

data := map[string]interface{}{
    "update": map[string]interface{}{
        "comment": []map[string]interface{}{
            {
                "add": map[string]string{
                    "body": "this is a body",
                },
            },
        },
    },
}

最新更新