In your provided data of json each key contains two values. That's the reason behind empty slices. Use slice of string in your struct to unmarshal the value.
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)
}
Output:
&{[John Jake] [999-999-999 12312-123-123]}
For required structure
{ Name: "John", Phone: "999-999-999" },
{ Name: "Jake", Phone: "12312-123-123" }
Edited:
Process the data coming from form to change the format of your structure.
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
", result)
}
Output:
[]stack.Person2{stack.Person2{Name:"John", Phone:"999-999-999"}, stack.Person2{Name:"Jake", Phone:"12312-123-123"}}
Playground Example to process the data
As @Adrain suggested it is better to use some kind of indexing with the field names for the form. It is also provided in gorilla/schema
package to name the values with indexes for saving multiple records.
<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>
Above form can be parsed to below struct which contains a slice of Phone:
type Person struct {
Name string
Phones []Phone
}