Golang : fmt.Println prints out empty data from struct
Problem :
Your code compiled successfully and there is no error indicator whatsoever. However, during runtime, the fmt.Println function prints out empty data that you expected from a struct that suppose to have unmarshaled JSON data. What's going on?
For example :
package main
import "fmt"
import "encoding/json"
func main() {
var v = []byte(`[
{
"name": "D***",
"email": "D***@gmail.com"
"gender": "Male",
"age": 27,
}
{
"name": "A***",
"email": "a@a.com"
"gender": "Female",
"age": 31,
}
]`)
type Person struct {
name string
email string
gender string
age int
}
var people []Person
err := json.Unmarshal(v, &people)
if err != nil {
}
fmt.Println(people)
}
http://play.golang.org/p/gHqiCLk-rV
will compile just fine, but will print out empty data.
Solution :
Use JSON Linter to validate the JSON data. ( http://jsonlint.com/ )
The variables names inside the Person struct starts with small cap, this means those variables are
private
type and cannot be displayed. Thus, this explains why the fmt.Println function prints out empty data. To fix the problem, change the variables names to start with big cap to make thempublic
type. See the fixed code at http://play.golang.org/p/xLfz_aofCQ
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+16.7k Golang : Merge video(OpenCV) and audio(PortAudio) into a mp4 file
+15.5k Golang : invalid character ',' looking for beginning of value
+7.9k Golang : Example of how to detect which type of script a word belongs to
+13.8k Golang : Qt progress dialog example
+22.8k Golang : Strings to lowercase and uppercase example
+11k Golang : Removes punctuation or defined delimiter from the user's input
+11.3k Golang : Proper way to test CIDR membership of an IP 4 or 6 address example
+12.8k Golang : Remove or trim extra comma from CSV
+15.7k Golang : Force download file example
+16.5k Golang : How to implement two-factor authentication?
+11.2k Golang : Simple image viewer with Go-GTK
+15.4k Golang : How to get Unix file descriptor for console and file