Golang을 사용하여 JSON HTTP 응답 구문 분석
제공된 JSON 응답에서 "ip" 값을 검색하려면 사용자 정의를 활용하는 것이 좋습니다. JSON 구조를 미러링하고 이에 따라 응답을 디코딩하는 구조체입니다. 다음 코드를 고려하세요.
import ( "bytes" "encoding/json" "fmt" "log" ) // Define structs to match the JSON structure type Example struct { Type string `json:"type"` Subsets []Subset `json:"subsets"` } type Subset struct { Addresses []Address `json:"addresses"` } type Address struct { IP string `json:"ip"` } func main() { // Define the JSON input m := []byte(`{"type":"example","data":{"name":"abc","labels":{"key":"value"}},"subsets":[{"addresses":[{"ip":"192.168.103.178"}],"ports":[{"port":80}]}]}`) // Create a reader from the JSON input r := bytes.NewReader(m) decoder := json.NewDecoder(r) // Decode the JSON into the Example struct val := &Example{} if err := decoder.Decode(val); err != nil { log.Fatal(err) } // Iterate over the Subsets and Addresses slices to access each IP for _, s := range val.Subsets { for _, a := range s.Addresses { fmt.Println(a.IP) } } }
이 접근 방식을 사용하면 JSON 응답을 사용자 정의 구조체로 디코딩할 수 있어 구조체 멤버(예: a.IP)에 액세스하여 슬라이스를 반복하고 특정 값을 검색하는 기능을 제공할 수 있습니다. 제공된 코드는 JSON 응답을 읽고, 이를 구조체로 디코딩하고, 특정 값을 추출하는 엔드투엔드 워크플로를 보여줍니다.
위 내용은 Golang의 JSON HTTP 응답에서 \'ip\' 값을 어떻게 추출할 수 있나요?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!