json – 如何正确地解组不同类型的数组?

前端之家收集整理的这篇文章主要介绍了json – 如何正确地解组不同类型的数组?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
只要我有键值对解组是非常简单的,但是我将如何以不同的顺序解组不同类型的数组?单个元素是明确定义和已知的,但顺序不是.

我无法想出一个美丽的解决方案.

我会尝试错误的所有元素吗?
是否有某种联合类型可以为我做这个?

playground version

package main

import (
    "encoding/json"
    "fmt"
)

var my_json string = `{
    "an_array":[
        "with_a string",{
            "and":"some_more","different":["nested","types"]
        }
    ]
}`

type MyInner struct {
    And     string
    Different   []string
}

type MyJSON struct {
    An_array []json.RawMessage
}

func main() {
    var my_json_test MyJSON

    e := json.Unmarshal([]byte(my_json),&my_json_test)
    if e != nil {
        fmt.Println(e)
    } else {
        for index,value := range my_json_test.An_array {
            fmt.Println("index: ",index)
            fmt.Println("value: ",string(value))
        }
        var my_inner MyInner
        err := json.Unmarshal(my_json_test.An_array[1],&my_inner)
        if err != nil {
            fmt.Println(err)
        } else {
            fmt.Println("inner structure: ",my_inner)
        }
    }
}

解决方法

Go官方博客有一篇关于 encoding/jsonJSON and GO的很好的文章.可以将“任意数据”解码为接口{},并使用类型断言来动态地确定类型.

您的代码可能被修改为:

package main

import (
    "encoding/json"
    "fmt"
)

var my_json string = `{
    "an_array":[
    "with_a string",{
        "and":"some_more","types"]
    }
    ]
}`

func WTHisThisJSON(f interface{}) {
    switch vf := f.(type) {
    case map[string]interface{}:
        fmt.Println("is a map:")
        for k,v := range vf {
            switch vv := v.(type) {
            case string:
                fmt.Printf("%v: is string - %q\n",k,vv)
            case int:
                fmt.Printf("%v: is int - %q\n",vv)
            default:
                fmt.Printf("%v: ",k)
                WTHisThisJSON(v)
            }

        }
    case []interface{}:
        fmt.Println("is an array:")
        for k,k)
                WTHisThisJSON(v)
            }

        }
    }
}

func main() {

    fmt.Println("JSON:\n",my_json,"\n")

    var f interface{}
    err := json.Unmarshal([]byte(my_json),&f)
    if err != nil {
        fmt.Println(err)
    } else {
        fmt.Printf("JSON: ")
        WTHisThisJSON(f)
    }
}

输出如下:

JSON:
 {
    "an_array":[
    "with_a string","types"]
    }
    ]
} 

JSON: is a map:
an_array: is an array:
0: is string - "with_a string"
1: is a map:
and: is string - "some_more"
different: is an array:
0: is string - "nested"
1: is string - "types"

它还不完整,但显示它将如何工作.

原文链接:https://www.f2er.com/js/154166.html

猜你在找的JavaScript相关文章