2017-12-18 7 views
-1

私はアプリケーションをGoに変換する新しいユーザーです。大文字なしでjson変数を返す

type Network struct { 
     Ssid  string 
     Security string 
     Bitrate string 
} 

func Scan(w http.ResponseWriter, r *http.Request) { 
     output := runcmd(scripts+"scan.sh", true) 
     bytes := []byte(output) 
     var networks []Network 
     json.Unmarshal(bytes, &networks) 
     w.Header().Set("Content-Type", "application/json") 
     json.NewEncoder(w).Encode(networks) 
} 

問題が返されるJSON変数に大文字を使用していない古いバージョンである:私は働いている次のようなものを持っています。

フロントエンドにssidが表示されないようにします。Ssidです。構造体の属性を小文字にすると、コードは非エクスポート変数になるので、もはや機能しません。

答えて

4

構造体のフィールド名がjsonフィールド名と一致しない場合は、フィールドタグを使用できます。 例:

Ssid string `json:"myOtherFieldName"` 

詳細はjson docsをお読みください。

1

学習のための非常に便利なこのツール:

https://mholt.github.io/json-to-go/

はそれをあなたはそれがgolangをお勧めしますしたいJSONの例を与えます。

JSON

{ 
    "ssid": "some very long ssid", 
    "security": "big secret", 
    "bitrate": 1024 
} 

はgolangを提案します:

type AutoGenerated struct { 
    Ssid  string `json:"ssid"` 
    Security string `json:"security"` 
    Bitrate int `json:"bitrate"` 
} 

今あなたが好きにAutogGenerated, Ssid, Security, Bitrateを変更することができます。

関連する問題