gpt4 book ai didi

go - 重复 formData 到 Go 结构

转载 作者:数据小太阳 更新时间:2023-10-29 03:11:06 24 4
gpt4 key购买 nike

我正在提交一个重复表单,其中生成的 formData 被解析为:

"Name":  {"John", "Jake"},
"Phone": {"999-999-999", "12312-123-123"},

但是,我想构造成

{ Name: "John", Phone: "999-999-999" }, 
{ Name: "Jake", Phone: "12312-123-123" }.

有人告诉我gorilla/schema , 很合适,但我在下面尝试了它,它产生了一个空 slice 。有什么我想念的吗?

package main

import (
"fmt"

"github.com/gorilla/schema"
)

type Person struct {
Name string
Phone string
}

func main() {
values := map[string][]string{
"Name": {"John", "Jake"},
"Phone": {"999-999-999", "12312-123-123"},
}
var persons []Person
decoder := schema.NewDecoder()
decoder.Decode(persons, values)
fmt.Println(persons)
}

最佳答案

在您提供的 json 数据中,每个键包含两个值。这就是空 slice 背后的原因。在结构中使用字符串片段来解码值。

package main

import (
"fmt"

"github.com/gorilla/schema"
)

type Person struct {
Name []string // this should be a slice since the key contains multiple values
Phone []string
}

type Person2 struct {
Name string
Phone string
}

func main() {
values := map[string][]string{
"Name": {"John", "Jake"},
"Phone": {"999-999-999", "12312-123-123"},
}
person := new(Person)
decoder := schema.NewDecoder()
decoder.Decode(person, values)
fmt.Println(person)
}

输出:

&{[John Jake] [999-999-999 12312-123-123]}

对于所需的结构

{ Name: "John", Phone: "999-999-999" }, 
{ Name: "Jake", Phone: "12312-123-123" }

已编辑:

处理来自表单的数据以更改结构的格式。

type Person2 struct {
Name string
Phone string
}

func processData(person *Person) {
var result []Person2
var person2 Person2
for i := 0; i < len(person.Name); i++ {
person2.Name = person.Name[i]
person2.Phone = person.Phone[i]
result = append(result, person2)
}
fmt.Printf("%#v\n", result)
}

输出:

[]stack.Person2{stack.Person2{Name:"John", Phone:"999-999-999"}, stack.Person2{Name:"Jake", Phone:"12312-123-123"}}

Playground Example处理数据

正如@Adrain 所建议的,最好对表单的字段名称使用某种索引。它也在 gorilla/schema 中提供包以命名带有索引的值以保存多条记录。

<form>
<input type="text" name="Name">
<input type="text" name="Phones.0.Label">
<input type="text" name="Phones.0.Number">
<input type="text" name="Phones.1.Label">
<input type="text" name="Phones.1.Number">
<input type="text" name="Phones.2.Label">
<input type="text" name="Phones.2.Number">
</form>

上面的表单可以解析为下面的结构,其中包含一段电话:

type Person struct {
Name string
Phones []Phone
}

关于go - 重复 formData 到 Go 结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51592161/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com