Convert Go structure to JSON

I am trying to convert a Go structure to JSON using the json package, but all I get is {} . I am sure that this is something completely obvious, but I do not 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 the following:

 $ 6g test.go && 6l -o test test.6 && ./test {} 
+136
json go
Nov 25 2018-11-11T00:
source share
4 answers

You need to export the User.name field User.name 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"} 
+269
Nov 25 2018-11-11T00:
source share

Related problem:

I had a problem converting the structure to JSON, sending it as a response from Golang, then, later, catch the same thing in JavaScript via Ajax.

Much time has been allocated, so post the solution here.

In Go:

 // web server type Foo struct { Number int `json:"number"` Title string `json:"title"` } foo_marshalled, err := json.Marshal(Foo{Number: 1, Title: "test"}) fmt.Fprint(w, string(foo_marshalled)) // write response to ResponseWriter (w) 

In JavaScript:

 // web call & receive in "data", thru Ajax/ other var Foo = JSON.parse(data); console.log("number: " + Foo.number); console.log("title: " + Foo.title); 

Hope this helps someone. Good luck.

+48
Jul 30 '15 at 15:12
source share

Structural values ​​are encoded as JSON objects. Each exported structure field becomes a member of the object if:

  • field tag "-" or
  • the field is empty, and its tag defines the option "omitempty".

Null values ​​are false, 0, any null pointer or interface value, as well as any array, fragment, map, or zero-length string. The default object key string is the name of the structural field, but it can be specified in the tag value of the structural field. The "json" key in the value of the struct field tag is the name of the key, followed by an optional comma and parameters.

+6
May 31 '14 at 18:17
source share

You can define your own MarshalJSON and UnmarshalJSON methods and intentionally control what should be included, for example:

 package main import ( "fmt" "encoding/json" ) type User struct { name string } func (u *User) MarshalJSON() ([]byte, error) { return json.Marshal(&struct { Name string 'json:"name"' }{ Name: "customized" + u.name, }) } func main() { user := &User{name: "Frank"} b, err := json.Marshal(user) if err != nil { fmt.Println(err) return } fmt.Println(string(b)) } 
0
Jul 01 '19 at 11:59
source share



All Articles