Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to marshal anonymous struct? [duplicate]

Tags:

struct

go

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

like image 958
Marcin Doliwa Avatar asked Jan 30 '18 16:01

Marcin Doliwa


1 Answers

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

like image 198
tom10271 Avatar answered Oct 03 '22 04:10

tom10271