4

I have the following JSON array that I'm trying to convert to a struct.

[
    {
        "titel": "test 1",
        "event": "some value",
        "pair": "some value",
        "condition": [
            "or",
            [
                "contains",
                "url",
                "/"
            ]
        ],
        "actions": [
            [
                "option1",
                "12",
                "1"
            ],
            [
                "option2",
                "3",
                "1"
            ]
        ]
    }, {
        "titel": "test 2",
        "event": "some value",
        "pair": "some value",
        "condition": [
            "or",
            [
                "contains",
                "url",
                "/"
            ]
        ],
        "actions": [
            [
                "option1",
                "12",
                "1"
            ],
            [
                "option2",
                "3",
                "1"
            ]
        ]
    }
]

This is the struct I've got so far:

type Trigger struct {
    Event     string        `json:"event"`  
    Pair      string        `json:"pair"`   
    Actions   [][]string    `json:"actions"`
    Condition []interface{} `json:"condition"`
}

type Triggers struct {
    Collection []Trigger
}

However, this does not really cover the "Condition" part. Ideally id like to have a structure for that as well.

1
  • 3
    Condition is an array and I think using []interface{} as you are is the most reasonable approach. It will be a pain to unwrap but since they have 2 types in the array and Go has a strict type system, there aren't a lot of options other than what you got or implementing UnmarshalJSON yourself to handle the special case in some other way. Commented Dec 29, 2015 at 19:31

1 Answer 1

3

Assuming that there can be only a single condition per item in the root array, you can try a struct below. This could make using Condition clear.

https://play.golang.org/p/WxFhBjJmEN

type Trigger struct {
    Event     string     `json:"event"`
    Pair      string     `json:"pair"`
    Actions   [][]string `json:"actions"`
    Condition Condition  `json:"condition"`
}

type Condition []interface{}

func (c *Condition) Typ() string {
    return (*c)[0].(string)
}

func (c *Condition) Val() []string {
    xs := (*c)[1].([]interface{})
    ys := make([]string, len(xs))
    for i, x := range xs {
        ys[i] = x.(string)
    }
    return ys
}

type Triggers struct {
    Collection []Trigger
}
Sign up to request clarification or add additional context in comments.

1 Comment

Simply awesome! This does precisely what I need. Thanks a ton for taking the time.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.