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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With