猿问

如何通过名称获取特定的 api,然后从此“Apis”结构列表中获取它的 ID?

type Apis struct {

    Items []struct {

        ID                    string `json:"id"`

        Name                  string `json:"name"`

        Description           string `json:"description"`

        CreatedDate           int    `json:"createdDate"`

        APIKeySource          string `json:"apiKeySource"`

        EndpointConfiguration struct {

            Types []string `json:"types"`

        } `json:"endpointConfiguration"`

    } `json:"items"`

}

这是我定义的结构,用于存储我以 json 格式获得的 API。如何通过名称获取特定 API,然后获取其 ID。例如,假设apiname == Shopping我希望将 Shopping API 的 ID 分配给id变量。


ps:我是golang的新手,非常感谢解释清楚的答案。多谢你们


交互式爱情
浏览 137回答 1
1回答

吃鸡游戏

在您的情况下Items是自定义结构的切片,因此您必须执行循环搜索,如下所示:package mainimport (    "encoding/json"    "fmt")type Apis struct {    Items []struct {        ID                    string `json:"id"`        Name                  string `json:"name"`        Description           string `json:"description"`        CreatedDate           int    `json:"createdDate"`        APIKeySource          string `json:"apiKeySource"`        EndpointConfiguration struct {            Types []string `json:"types"`        } `json:"endpointConfiguration"`    } `json:"items"`}func main() {    // Some JSON example:    jsonStr := `{"items": [{"id":"1","name":"foo"},{"id":"2","name":"bar"}]}`    // Unmarshal from JSON into Apis struct.    apis := Apis{}    err := json.Unmarshal([]byte(jsonStr), &apis)    if err != nil {        // error handling    }    // Actual search:    nameToFind := "bar"    for _, item := range apis.Items {        if item.Name == nameToFind {            fmt.Printf("found: %+v", item.ID)            break        }    }}使用自定义结构而不是切片会更好map,因此您可以执行以下操作:package mainimport (    "encoding/json"    "fmt")type Apis struct {    Items map[string]struct {        ID                    string `json:"id"`        Name                  string `json:"name"`        Description           string `json:"description"`        CreatedDate           int    `json:"createdDate"`        APIKeySource          string `json:"apiKeySource"`        EndpointConfiguration struct {            Types []string `json:"types"`        } `json:"endpointConfiguration"`    } `json:"items"`}func main() {    // Some JSON example:    jsonStr := `{"items": {"foo":{"id":"1","name":"foo"},"bar":{"id":"2","name":"bar"}}}`    // Unmarshal from JSON into Apis struct.    apis := Apis{}    err := json.Unmarshal([]byte(jsonStr), &apis)    if err != nil {        // error handling    }    // Actual search:    nameToFind := "bar"    item, found := apis.Items[nameToFind]    if !found {        fmt.Printf("item not found")    }    fmt.Printf("found: %+v", item)}重要提示:使用切片,算法的复杂性将O(n)与地图有关 -O(1)这会更好(这是最好的)。
随时随地看视频慕课网APP

相关分类

Go
我要回答