使用 golang 的 encoding/json 读取嵌套的 json 数据

Reading nested json data with golang's encoding/json

我无法获得正确的结构定义来捕获保存在变量中的嵌套 json 数据。我的代码片段如下:

package main

import "fmt"
import "encoding/json"

type Data struct {
    P string `json:"ports"`
    Ports struct {
         Portnums []int
    }
    Protocols []string `json:"protocols"`
}

func main() {
        y := `{
                "ports": {
            "udp": [
                1, 
                30
            ], 
            "tcp": [
                100, 
                1023
            ]
            }, 
            "protocols": [
            "tcp", 
            "udp"
            ]
    }`
    var data Data
    e := json.Unmarshal([]byte(y), &data)
    if e == nil {
        fmt.Println(data)
    } else {
        fmt.Println("Failed:", e)
    }

}

$ go run foo.go 
Failed: json: cannot unmarshal object into Go value of type string

这对我有用(见上面对你的问题的评论)GoPlay

type Data struct {
    Ports struct {
        Tcp []float64 `json:"tcp"`
        Udp []float64 `json:"udp"`
    } `json:"ports"`
    Protocols []string `json:"protocols"`
}

func main() {
    y := `{
                "ports": {
            "udp": [
                1, 
                30
            ], 
            "tcp": [
                100, 
                1023
            ]
            }, 
            "protocols": [
            "tcp", 
            "udp"
            ]
    }`
    d := Data{}
    err := json.Unmarshal([]byte(y), &d)
    if err != nil {
        fmt.Println("Error:", err.Error())
    } else {
        fmt.Printf("%#+v", d)
    }

}

输出

main.Data{
    Ports:struct { 
        Tcp []float64 "json:\"tcp\"";
        Udp []float64 "json:\"udp\"" 
    }{
        Tcp:[]float64{100, 1023},
        Udp:[]float64{1, 30}
    },
    Protocols:[]string{"tcp", "udp"}
}