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

时间:2015-03-13 20:56:49

标签: json encoding go

我无法获得结构的正确定义,以捕获保存在变量中的嵌套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

1 个答案:

答案 0 :(得分:2)

这适用于我(请参阅上述问题的评论) 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"}
}