5

Why do I get {} when trying to marshal an anonymous struct?

package main

import (
    "encoding/json"
    "fmt"
    "os"
)

func main() {
    js, err := json.Marshal(struct{id int}{123})
    if err != nil {
        fmt.Println("error:", err)
    }
    os.Stdout.Write(js)
}

https://play.golang.org/p/lEqJ1uj1ezS

jonroethke
  • 1,152
  • 2
  • 8
  • 16
Marcin Doliwa
  • 3,639
  • 3
  • 37
  • 62

2 Answers2

12

https://play.golang.org/p/XNAKovWGhxk

package main

import (
    "encoding/json"
    "fmt"
    "os"
)

func main() {
    jsonString, err := json.Marshal(
        struct{
            Id int `json:"theKeyYouWantToUse"`
        } {
            123
        },
    )

    if err != nil {
        fmt.Println("error:", err)
    }

    os.Stdout.Write(jsonString)
}

You are not exporting id attribute, change it to Id

tom10271
  • 4,222
  • 5
  • 33
  • 62
  • The json field tag is not necessary unless you need a different field name in the struct vs. the JSON. – Adrian Jan 30 '18 at 16:11
8

If you use following struct, Marshal method will ignore id as it is not exported.

struct{id int}{123}

You need to export them to keep them in conversion process.

In Go, a name is exported if it begins with a capital letter

js, _ := json.Marshal(struct{Id int}{123})
os.Stdout.Write(js)
// {"Id":123}
Shahriar
  • 13,460
  • 8
  • 78
  • 95