我如何通过名称获取特定的 api 然后从这个 "Apis" 结构列表中获取它的 ID?

How do I get a specific api by it's name and then get it's ID from this "Apis" list of structs?

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 格式获得的 APIs。如何通过名称获取特定的 API 然后获取其 ID。例如,假设 apiname == Shopping,我想将购物 API 的 ID 分配给 id 变量。

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

在您的情况下,Items 是自定义结构的切片,因此您必须执行循环搜索,如下所示:

package main

import (
    "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 个自定义结构而不是 slice,所以你可以这样做:

package main

import (
    "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)
}

重要:使用 slice 算法的复杂性将 O(n) 与 map - O(1) 更好(尽可能最好)。