Golang如何获取从REST API JSON响应(从multistructure)特定密钥
必需的JSON特定的密钥:status -> name
和id
值仅Golang如何获取从REST API JSON响应(从multistructure)特定密钥
getUrl := "https://www.test.com" reqTransitionID, err := http.NewRequest("GET", getUrl, nil)
respTransitionID, err := client.Do(reqTransitionID)
if err != nil {
log.Fatal(err)
}
defer respTransitionID.Body.Close()
type Statuskey struct {
Id string `json:"id"`
Name string `json:"name"`
}
type TransitionID struct {
Status Statuskey `json:"status"`
}
jsonData, errrr := ioutil.ReadAll(respTransitionID.Body)
if errrr != nil {
fmt.Println("Error reading JSON data:", errrr)
return
}
fmt.Println(string(jsonData))
var ss TransitionID
json.Unmarshal(jsonData, &ss)
fmt.Println(ss.Status)
fmt.Println(ss.Status.Id)
fmt.Println(ss.Status.Name)
的json响应:
{ "expand":"demo",
"id":"825",
"self":"TEST",
"key":"TEST",
"fields":{
"status":{
"self":"tst",
"description":"test",
"iconUrl":"test",
"name":"Closed",
"id":"6",
"statusCategory":{
"self":"test",
"id":3,
"key":"done",
"colorName":"green",
"name":"Done"
}
}
}
}
回答:
jsonDataSrc, errrr := ioutil.ReadAll(respTransitionID.Body) if errrr != nil {
fmt.Println("Error reading JSON data:", errrr)
return
}
type Status struct {
Name string `json:"name"`
Id string `json:"id"`
}
type Fields struct {
Status Status `json:"status"`
}
type JsonResponse struct {
Fields Fields `json:"fields"`
}
res := JsonResponse{}
json.Unmarshal([]byte(jsonDataSrc), &res)
fmt.Println(res.Fields.Status.Id)
fmt.Println(res.Fields.Status.Name)
输出 - 6 已关闭
以上是 Golang如何获取从REST API JSON响应(从multistructure)特定密钥 的全部内容, 来源链接: utcz.com/qa/257993.html