patterngoCritical
Converting Go struct to JSON
Viewed 0 times
structconvertingjson
Problem
I am trying to convert a Go struct to JSON using the
Then when I try to run it I get this:
json package but all I get is {}. I am certain it is something totally obvious but I don't see it.package main
import (
"fmt"
"encoding/json"
)
type User struct {
name string
}
func main() {
user := &User{name:"Frank"}
b, err := json.Marshal(user)
if err != nil {
fmt.Printf("Error: %s", err)
return;
}
fmt.Println(string(b))
}Then when I try to run it I get this:
$ 6g test.go && 6l -o test test.6 && ./test
{}Solution
You need to export the
Output:
User.name field so that the json package can see it. Rename the name field to Name.package main
import (
"fmt"
"encoding/json"
)
type User struct {
Name string
}
func main() {
user := &User{Name: "Frank"}
b, err := json.Marshal(user)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(string(b))
}Output:
{"Name":"Frank"}Code Snippets
package main
import (
"fmt"
"encoding/json"
)
type User struct {
Name string
}
func main() {
user := &User{Name: "Frank"}
b, err := json.Marshal(user)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(string(b))
}{"Name":"Frank"}Context
Stack Overflow Q#8270816, score: 563
Revisions (0)
No revisions yet.