在Golang中为复杂的JSON数组创建结构

时间:2015-12-29 19:28:09

标签: json go

我有以下JSON数组,我正在尝试将其转换为结构。

[
    {
        "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"
            ]
        ]
    }
]

这是我到目前为止的结构:

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

type Triggers struct {
    Collection []Trigger
}

然而,这并没有涵盖“条件”部分。理想情况下,我也想拥有一个结构。

1 个答案:

答案 0 :(得分:2)

假设根数组中每个项目只能有一个条件,您可以尝试下面的结构。这可以使Condition清除。

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
}