2016-09-30 2 views
1

私は、コードのこの部分を簡素化することができるか知りたいのですが:のような構造体を宣言せずにJSONとしてエンコードされた構造体を送信する方法はありますか?

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

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

は何か:

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

^これは私を与える:syntax error: missing operand

の取り除くために:

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

ありがとうございました。私の英語のために申し訳ありません。

答えて

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

は働くだろう - 文字列キーを持つマップをオブジェクトとしてJSONにエンコードすると、あなたが彼らと一緒に好きな構築することができます。それは短くはありませんが、ヘルパータイプを避けています。

+0

ありがとうございます!できます ! – Algoru

1

hobbの回答の代わりに、匿名の構造体を使用することもできます。

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

ありがとう!ちゃんと覚えておきますよ – Algoru

関連する問題