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)
                    }
                }
            }
        }
    }
    
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改