无论如何,不​​声明结构就将编码的结构作为JSON发送?

无论如何,不​​声明结构就将编码的结构作为JSON发送?

问题描述:

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.

我想知道如何简化这段代码: p>

  type PP struct {
 Profile_picture string`json:“ profile_picture”`
} 
 
json.NewEncoder(w).Encode(PP {result.Profile_picture})
  code>  pre  > 
 
 

类似的东西: p>

  json.NewEncoder(w).Encode({result.Profile_picture})
  code>  pre>  
 
 

^这给了我:语法错误:缺少操作数 code> p>

并摆脱了: p> type PP struct { Profile_picture字符串`json:“ profile_picture”` } code> pre>

谢谢。 抱歉,我的英文。 p> div>

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.

Alternatively to hobb's answer, you could also use an anonymous struct.

json.NewEncoder(w).Encode(
    struct {
        Pp string `json:"profile_picture"`
    }{result.Profile_picture},
)