2017-12-18 6 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을보고 싶습니다. 구조체의 속성을 소문자로 만들면 코드는 더 이상 unexported 변수가되므로 작동하지 않습니다.

답변

4

구조체의 필드 이름이 json 필드 이름과 일치하지 않으면 필드 태그를 사용할 수 있습니다. 예 :

Ssid string `json:"myOtherFieldName"` 

은 자세한 내용은 json docs을 읽어 보시기 바랍니다.

1

이 도구는 학습에 매우 편리합니다 :

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

그것을 당신이 golang을 권장합니다 원하는 JSON의 예를 들어주세요.

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

지금 당신은 당신이 원하는대로에 AutogGenerated, Ssid, Security, Bitrate을 변경할 수 있습니다

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

JSON 는 golang을 제안합니다.