0

I can't get the correct definition for my structs to capture the nested json data saved in a variable. My code snippet is as below:

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
2
  • You are trying to unmarshal the data y into a pointer to y. Your second argument to Unmarshal should be &data, not &y Commented Mar 13, 2015 at 21:16
  • Sorry that was a typo during copy+paste. Unmarshaling still fails :( Commented Mar 13, 2015 at 21:18

1 Answer 1

2

This works for me (see comment to your question above) 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)
    }

}

OUTPUT

main.Data{
    Ports:struct { 
        Tcp []float64 "json:\"tcp\"";
        Udp []float64 "json:\"udp\"" 
    }{
        Tcp:[]float64{100, 1023},
        Udp:[]float64{1, 30}
    },
    Protocols:[]string{"tcp", "udp"}
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.