unmarshal map of slices to struct

581 views
Skip to first unread message

Sergey Gavruk

unread,
Oct 6, 2013, 3:41:27 PM10/6/13
to golan...@googlegroups.com
Hello.

I have an object 
params map[string][]string
Is there any quick way to convert this object to any struct type, like json unmarshal?

Sergey Gavruk

unread,
Oct 7, 2013, 5:03:34 AM10/7/13
to golan...@googlegroups.com
My usecase:

I want to parse request.Form (which is map[string][]string) to any struct. I can use reflection, but its very complicated. I hope there is any way to do it more simple.

Tamás Gulácsi

unread,
Oct 7, 2013, 7:52:57 AM10/7/13
to golan...@googlegroups.com
If you know the target struct beforehand, then you can write code for it. If not, then only reflection can help. Encoding/json.Marshal can marshal such datatype, then you can Unmarshal it to a properly tagged struct, but this is a very lazy solution.

Athiwat Chunlakhan

unread,
Oct 7, 2013, 8:43:21 AM10/7/13
to golan...@googlegroups.com
Take a look at http://www.gorillatoolkit.org/pkg/schema
It's use to convert http stuff (which is a normal map)

Sergey Gavruk

unread,
Oct 7, 2013, 9:09:23 AM10/7/13
to Athiwat Chunlakhan, golang-nuts
Wow, that exactly what I need. Thank you!


--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.



--
Best regards,
Sergey Gavruk

Kevin Gillette

unread,
Oct 7, 2013, 4:16:47 PM10/7/13
to golan...@googlegroups.com
schema is fairly useful in practice, though it has a few limitations, such as a rather non-idiomatic style for registering custom unmarshalers (the idiomatic style would be to not register anything at all, but to define methods akin to json.Unmarshaler).

Derek Perkins

unread,
Jul 15, 2014, 11:53:57 PM7/15/14
to golan...@googlegroups.com
On Monday, October 7, 2013 5:52:57 AM UTC-6, Tamás Gulácsi wrote:
If you know the target struct beforehand, then you can write code for it. If not, then only reflection can help. Encoding/json.Marshal can marshal such datatype, then you can Unmarshal it to a properly tagged struct, but this is a very lazy solution.

Tamás - Assuming I had a very simple struct like below, how would I write my UnmarshalJSON function to not use reflection?

type Mytest struct {
Field1 int32
Field2 string
}

Tamás Gulácsi

unread,
Jul 16, 2014, 3:06:38 AM7/16/14
to golan...@googlegroups.com
For such small structs you can write a json parser by hand, but using a generator (such as https://github.com/benbjohnson/megajson/blob/master/README.md) is less error prone, imho.
Reply all
Reply to author
Forward
0 new messages