在Golang中使用sjson将JSON中的数组递归更改为非数组

时间:2019-03-19 04:09:44

标签: arrays json go marshalling

我要做什么:

将JSON文件中所有长度为1的数组转换为非数组。

例如

输入:{"path": [{"secret/foo": [{"capabilities": ["read"]}]}]}

输出:{"path": {"secret/foo": {"capabilities": "read"}}}

我无法使用Structs,因为JSON格式会有所不同...

现在我至少设法检测出1个长度切片:

package main

import (
    "encoding/json"
    "fmt"
)

func findSingletons(value interface{}) {
    switch value.(type) {
    case []interface{}:
        if len(value.([]interface{})) == 1 {
            fmt.Println("1 length array found!", value)
        }
        for _, v := range value.([]interface{}) {
            findSingletons(v)
        }
    case map[string]interface{}:
        for _, v := range value.(map[string]interface{}) {
            findSingletons(v)
        }
    }
}

func removeSingletonsFromJSON(input string) {
    jsonFromInput := json.RawMessage(input)
    jsonMap := make(map[string]interface{})
    err := json.Unmarshal([]byte(jsonFromInput), &jsonMap)

    if err != nil {
        panic(err)
    }

    findSingletons(jsonMap)

    fmt.Printf("JSON value of without singletons:%s\n", jsonMap)
}

func main() {
    jsonParsed := []byte(`{"path": [{"secret/foo": [{"capabilities": ["read"]}]}]}`)
    removeSingletonsFromJSON(string(jsonParsed))
    fmt.Println(`Should have output {"path": {"secret/foo": {"capabilities": "read"}}}`)
}

哪个输出

1 length array found! [map[secret/foo:[map[capabilities:[read]]]]]
1 length array found! [map[capabilities:[read]]]
1 length array found! [read]
JSON value of without singletons:map[path:[map[secret/foo:[map[capabilities:[read]]]]]]
Should have output {"path": {"secret/foo": {"capabilities": "read"}}}

但是我不确定如何将它们更改为非数组...

1 个答案:

答案 0 :(得分:2)

类型开关是您的朋友:


        switch t := v.(type) {
        case []interface{}:
            if len(t) == 1 {
                data[k] = t[0]

您可以使用递归来删除内部元素,如下所示:

func removeOneElementSlice(data map[string]interface{}) {
    for k, v := range data {
        switch t := v.(type) {
        case []interface{}:
            if len(t) == 1 {
                data[k] = t[0]
                if v, ok := data[k].(map[string]interface{}); ok {
                    removeOneElementSlice(v)
                }
            }
        }
    }
}

我会做this进行转换
{"path":[{"secret/foo":[{"capabilities":["read"]}]}]}

 {"path":{"secret/foo":{"capabilities":"read"}}}

package main

import (
    "encoding/json"
    "fmt"
    "log"
)

func main() {
    s := `{"path":[{"secret/foo":[{"capabilities":["read"]}]}]}`
    fmt.Println(s)
    var data map[string]interface{}
    if err := json.Unmarshal([]byte(s), &data); err != nil {
        panic(err)
    }

    removeOneElementSlice(data)

    buf, err := json.Marshal(data)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(string(buf)) //{"a":"a","n":7}
}
func removeOneElementSlice(data map[string]interface{}) {
    for k, v := range data {
        switch t := v.(type) {
        case []interface{}:
            if len(t) == 1 {
                data[k] = t[0]
                if v, ok := data[k].(map[string]interface{}); ok {
                    removeOneElementSlice(v)
                }
            }
        }
    }
}