gpt4 book ai didi

json - 错误 : interface conversion interface {} is []interface {}, 不是映射 [字符串] 接口(interface) {}

转载 作者:行者123 更新时间:2023-12-01 22:32:53 25 4
gpt4 key购买 nike

我正在构建一个项目,该项目从用户那里获取一个术语,然后执行谷歌搜索并返回一个 json 格式的标题列表。

我正在使用 serpwow API 来执行谷歌搜索并试图解析响应。

但是我收到的错误是:

panic: interface conversion: interface {} is []interface {}, not map[string]interface {}.

我查看了各种表格并尝试了解映射的工作原理,但我不确定为什么在这种情况下,我的映射不起作用。有机结果表如下所示:
"organic_results": [
{
"position": 1,
"title": "The 10 Best Pizza Places in Dublin - TripAdvisor",
"link": "https://www.tripadvisor.ie/Restaurants-g186605-c31-Dublin_County_Dublin.html",
"domain": "www.tripadvisor.ie",
"displayed_link": "https://www.tripadvisor.ie › ... › County Dublin › Dublin",
"snippet": "Best Pizza in Dublin, County Dublin: Find TripAdvisor traveller reviews of Dublin Pizza places and search by price, location, and more.",
"prerender": false,
"snippet_matched": [
"Pizza",
"Pizza"
],
"cached_page_link": "https://webcache.googleusercontent.com/search?q=cache:OS-Ar9hB_ngJ:https://www.tripadvisor.ie/Restaurants-g186605-c31-Dublin_County_Dublin.html+&cd=4&hl=en&ct=clnk&gl=ie",
"related_page_link": "https://www.google.com/search?q=related:https://www.tripadvisor.ie/Restaurants-g186605-c31-Dublin_County_Dublin.html+pizza&tbo=1&sa=X&ved=2ahUKEwicjYKvvNjmAhVoSBUIHa9MBhcQHzADegQIARAH",
"block_position": 2
},

这是我的代码片段:
package main

import (
"fmt"
"strings"
serpwow "github.com/serpwow/google-search-results-golang"
)

func main() {
// set API key
apiKey := "Key_Hidden"

//read term to search
fmt.Print("What term would you like to search in google? ")
var term string
fmt.Scanln(&term)

// set up our search parameters
parameters := map[string]interface{}{
"q": term,
}

// retrieve the search results as JSON
response, error := serpwow.GetJSON(parameters, apiKey)

// print the response, or error, if one occurred
if error != nil {
fmt.Println(error)
} else {
//extract title from organic results
//result := fmt.Sprintf("%v", response["organic_results"].(map[string]interface{})["title"])
for _, item := range response["organic_results"].([]interface{}) {
fmt.Sprintf("%v", item.(map[string]interface{})["title"])
}
//s := []string{result, "\n"}
//fmt.Printf(strings.Join(s, " "))

}

}
有人可以帮我弄清楚我的逻辑哪里错了吗?

最佳答案

response["organic_results"]对应于 JSON 数组“organic_results”,因此它不是 map[string]interface{} , 但是一个 []interface .有多个结果,而不是一个。

for _,item:=range respose["organic_results"].([]interface{}) {
fmt.Printf("%v", item.(map[string]interface{})["title"])
}

关于json - 错误 : interface conversion interface {} is []interface {}, 不是映射 [字符串] 接口(interface) {},我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59759095/

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