Algoru Algoru - 1 year ago 59
JSON Question

Is there anyway to send an encoded struct as JSON without declaring a struct?

I would like to know how I could simplify this piece of code:

type PP struct {
Profile_picture string `json:"profile_picture"`
}

json.NewEncoder(w).Encode(PP {result.Profile_picture})


Something like:

json.NewEncoder(w).Encode({result.Profile_picture})


^ this give me:
syntax error: missing operand


And to get rid of:

type PP struct {
Profile_picture string `json:"profile_picture"`
}


Thanks. Sorry for my english.

Answer Source
json.NewEncoder(w).Encode(
    map[string]string{"profile_picture": result.Profile_picture},
)

would work — maps with string keys encode to JSON as objects, and you can build up whatever you like with them. It's not shorter, but it does avoid the helper type.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download