gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 22:21:05 26 4
gpt4 key购买 nike

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的新手,一个很好解释的答案将不胜感激。
谢谢你们

最佳答案

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

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时,算法的复杂性将是带有 map 的 O(n)- O(1),这会更好(最好是可能的)。

关于api - 如何通过名称获取特定的api,然后从此“Apis”结构列表中获取其ID?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63518684/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com