Go 如何解析表单post中的数组

Go 如何解析表单post中的数组,go,Go,我现在有一个表单帖子,像 { "stuff":"cool text", "otherthing":"neat thing", "captions":[ {"first":"the list", "second":"how are you"}, {"first":"wow", etc.... ] } 现在我不知道会有多少字幕。它可能是数组中的一个,也可能是二十个 我还建立了两个结构 type ThingContext struct { S

我现在有一个表单帖子,像

{
 "stuff":"cool text",
 "otherthing":"neat thing",
 "captions":[
     {"first":"the list",
     "second":"how are you"},
     {"first":"wow",
     etc....
  ]
}
现在我不知道会有多少字幕。它可能是数组中的一个,也可能是二十个

我还建立了两个结构

type ThingContext struct {
    Stuff       string  `json:"stuff"`
    OtherThing  string  `json:"otherthing"`
    Captions    []ArrayText `json:"captions"`
}

type ArrayText struct {
    First    string  `json:"first"`
    Second   string  `json:"second"`
}
在我的golang函数中,我有这样的东西

func (c *ThingContext) SetThingContext(rw web.ResponseWriter, req *web.Request, next web.NextMiddlewareFunc) {
    if err := req.ParseForm(); err != nil {
    }
    c.Stuff = req.FormValue("stuff")
    c.OtherThing = req.FormValue("otherthing")
}
在我尝试解析数组之前,这一切都很正常。 当我按照
c.Captions=req.ParseForm(“字幕”)
我得到了错误

.cannot use req.Request.ParseForm("captions") (type error) as type []ArrayText in assignment

你做得对,除了作业。运行req.Request.ParseForm()时,它将填充req.Request.Form和req.Request.PostForm结构,而不是返回值或传递对缓冲区的引用

所以而不是

c.Captions = req.Request.ParseForm()
看起来更像

err := req.Request.ParseForm()
//check for errors as usual here
c.Captions = req.Request.Form
//or
c.Captions = req.Request.PostForm
从这个方向接近它会让你走上正确的轨道

干杯!
Taylor

它给了我
不能在赋值中使用req.Request.Form(type url.Values)作为类型[]ArrayText
,所以我可能不得不做
c.Captions=req.Request.Form[“Captions”]
?你的思路是对的。您可能希望使用encoding/json内置库将数据打包到您的结构中。godoc for json非常令人困惑,但本页有一个不错的解释。因此,对于封送拆收器,您有几个选项,如果您有原始json数据,请将数据读入解组器,或者您可以解析url.Values,一旦您对url.Values调用.Encode(),它应该成为一个简单的字符串。抱歉,这里有多个新帖子。