json objects

96 views
Skip to first unread message

Hamsa Hesham

unread,
Dec 25, 2020, 6:25:56 PM12/25/20
to golang-nuts
package main
import "encoding/json"
import "log"
import "fmt"

type book struct {
    ID        int
    title     string
    pubDate   string
    author    string
    genre     string
    publisher string
    language  string
}
func main(){
b := book{
    ID:    1,
    title:   "Standard",
    pubDate:      "Standard",
    author: "Second-rate",
    genre: "Standard",
    publisher: "Standard",
    language: "Standard",
}

var jsonData []byte
jsonData, err := json.Marshal(b)
if err != nil {
    log.Println(err)
}
fmt.Println(string(jsonData))

}

The output is {"ID":1}  .. why?!!

Amit Saha

unread,
Dec 25, 2020, 6:30:38 PM12/25/20
to Hamsa Hesham, golang-nuts
Your struct fields will need to start with a capital letter to be exportable into JSON. Since ID is the only field here, you only see that in your output.


--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/44b561be-30eb-48cb-ae0c-5d56f09e1c2cn%40googlegroups.com.

Charles Radke

unread,
Dec 25, 2020, 6:53:02 PM12/25/20
to Amit Saha, Hamsa Hesham, golang-nuts
Try to export your struct fields. 

Sent from my iPhone

On Dec 25, 2020, at 6:30 PM, Amit Saha <amits...@gmail.com> wrote:



Roland Müller

unread,
Jan 1, 2021, 11:07:06 AM1/1/21
to Amit Saha, Hamsa Hesham, golang-nuts
To have a JSon format with lower-case field names one has to (1) use field names beginning with upper case - to enable export and (2) use json annotations to force a field name.
Just have a look at the following example: 


Reply all
Reply to author
Forward
0 new messages