mjhd
mjhd

Reputation: 65

Create struct for complex JSON array in Golang

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.

Upvotes: 4

Views: 984

Answers (1)

kopiczko
kopiczko

Reputation: 3058

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
}

Upvotes: 3

Related Questions