How to define struct with defined properties that is also a map

132 views
Skip to first unread message

David Karr

unread,
Sep 12, 2024, 6:30:30 PM9/12/24
to golang-nuts
This is probably basic, but I'm working on some code that unmarshals JIRA tickets (just for some context). Examining the Json output, there is a big "fields" object that mostly contains custom fields, but also some defined fields. Right now, I defined "Fields" as a "map[string]any", which is appropriate for the custom fields. However, I would really like to define something like this:

    type JIRAFields struct {
        map[string]any
        Parent JIRAParent
    }
    type JIRAParent struct {
        ...
    }

So I could reference a custom field like "Fields[key]", but the parent field with "Fields.Parent".

I'm certain the syntax I have so far isn't correct, as it flags the "map" saying "}" was expected.

burak serdar

unread,
Sep 12, 2024, 6:39:41 PM9/12/24
to David Karr, golang-nuts
The current json implementation in the stdlib does not support a
catchall like that. Also, you cannot embed a map in a struct.

You can replace JIRAFields with a map[string]any. If there are keys
with known structures, you can do a map[string]json.RawMessage, and
then you can do json.Unmarshal(fields[knownKey],&knownStruct) for
those keys whose structure you know.

Alternatively, you can use a map[string]any, and use the mapstructure
library to unmarshal a map[string]any to a known struct.
> --
> 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.
> To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/CAA5t8VqfpZ7og6Zxobcy388Zbyj%2BnTGc-J0gW_LBj9ngrErg4w%40mail.gmail.com.

twp...@gmail.com

unread,
Sep 13, 2024, 9:31:07 AM9/13/24
to golang-nuts
Also, quick plug for
which will generate type-safe Go structs for you for all fields. Just throw a bunch of JIRA JSON responses at it.

Regards,
Tom

Reply all
Reply to author
Forward
0 new messages