doubaoguo7469 2019-03-19 04:09
浏览 159
已采纳

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

What I'm trying to do:

Transform all arrays of length 1 in a JSON file to non arrays.

e.g.

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

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

I can't use Structs as the JSON format will vary...

Right now I've managed to at least detect the 1 length slices:

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
", jsonMap)
}

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

Which outputs

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"}}}

But I'm not sure how I can change them into non-arrays...

  • 写回答

1条回答 默认 最新

  • doulang5323 2019-03-19 04:45
    关注

    The type switch is your friend:

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

    And you may use recursion to remove inside elements, like so:

    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)
                    }
                }
            }
        }
    }
    

    I would do this to convert
    {"path":[{"secret/foo":[{"capabilities":["read"]}]}]}
    to
    {"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)
                    }
                }
            }
        }
    }
    
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 python天天向上类似问题,但没有清零
  • ¥30 3天&7天&&15天&销量如何统计同一行
  • ¥30 帮我写一段可以读取LD2450数据并计算距离的Arduino代码
  • ¥15 C#调用python代码(python带有库)
  • ¥15 矩阵加法的规则是两个矩阵中对应位置的数的绝对值进行加和
  • ¥15 活动选择题。最多可以参加几个项目?
  • ¥15 飞机曲面部件如机翼,壁板等具体的孔位模型
  • ¥15 vs2019中数据导出问题
  • ¥20 云服务Linux系统TCP-MSS值修改?
  • ¥20 关于#单片机#的问题:项目:使用模拟iic与ov2640通讯环境:F407问题:读取的ID号总是0xff,自己调了调发现在读从机数据时,SDA线上并未有信号变化(语言-c语言)