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.

0

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.