0

simple go-lang program for parsing json string into self-defined structure.

package main

import (
    "encoding/json"
    "fmt"
)

type IpInfo struct {
    ip string `json:"ip"`
}

type MyData struct {
    msg string `json:"msg"`
    status_code int `json:"status_code"`
    data []IpInfo `json:"data"`
}

func main() {
    json_data := []byte(`{"msg": "success", "status_code": 0, "data": [{"ip": "127.0.0.1"}]}`)
    my_data := MyData{}
    err := json.Unmarshal(json_data, &my_data)
    if err != nil {
        fmt.Println("error:", err)
    }
    fmt.Println(my_data.msg)
}

I got nothing after ran this code, however "success" was expected.

baduker
  • 19,152
  • 9
  • 33
  • 56
James Tang
  • 29
  • 1

1 Answers1

3

You have to export the fields from you struct.

package main

import (
    "encoding/json"
    "fmt"
)

type IpInfo struct {
    Ip string `json:"ip"`
}

type MyData struct {
    Msg        string             `json:"msg"`
    StatusCode int                `json:"status_code"`
    Data       []struct{ IpInfo } `json:"data"`
}

func main() {
    jsonData := []byte(`{"msg": "success", "status_code": 0, "data": [{"ip": "127.0.0.1"}]}`)
    myData := MyData{}
    err := json.Unmarshal(jsonData, &myData)

    if err != nil {
        fmt.Println("error:", err)
    }

    fmt.Println(myData.Msg)
}

Output: success

Also, I'd recommend reading on Go's naming conventions and formatting here. And don't forget to run go fmt on your file.

baduker
  • 19,152
  • 9
  • 33
  • 56