为了账号安全,请及时绑定邮箱和手机立即绑定

错误:接口转换 interface {} 是 []interface {}

错误:接口转换 interface {} 是 []interface {}

Go
皈依舞 2022-05-05 17:39:45
我正在构建一个项目,该项目从用户那里获取一个术语,然后执行谷歌搜索并返回一个 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 mainimport (    "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)    }}有人可以帮我弄清楚我的逻辑哪里错了吗?
查看完整描述

3 回答

?
天涯尽头无女友

TA贡献1831条经验 获得超9个赞

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


for _,item:=range respose["organic_results"].([]interface{}) {

    fmt.Printf("%v", item.(map[string]interface{})["title"])

}


查看完整回答
反对 回复 2022-05-05
?
炎炎设计

TA贡献1808条经验 获得超4个赞

正如您在 JSON 中看到的,organic_results的值是 JSON 数组,而不是对象;数组的每个元素都是一个对象。因此,您不能断言organic_resultsmap[string]interface{}因为正如错误所述,它不是地图,而是[]interface. 例如,您可以这样做:

    result := fmt.Sprintf("%v", response["organic_results"].([]interface{})[0].(map[string]interface{})["title"])

但是当然这只会让你得到第一个结果的标题,如果结果为空,它会崩溃。您必须将其视为“从响应中获取标题”而不是“处理返回的零个或多个结果” - 即您可能希望循环organic_results并对每个结果对象执行某些操作。


查看完整回答
反对 回复 2022-05-05
?
九州编程

TA贡献1785条经验 获得超4个赞

有时,逆向工程也有效,尽管我定义的所有类型看起来都非常直观,但我也遇到了无法解组自定义 JSON 文件的问题。


type ResourceConfig struct {

    ResourceType map[string]AlphabetType  `json:"resourceType"`

    RedisConfig  RedisConfigT               `json:"redisConfig"`

}


type AlphabetType struct {

    XXX  []string `json:"xxx"`

    YYY []string `json:"yyy"`

}


type RedisConfigT struct {

    Broker string     `json:"broker"`

    DB     string     `json:"db"`

}

json 看起来像这样:


{

        "resourceType": [

                {"/abcdefg": [{"xxx": ["/vrf", "/lsp", "/vpn"], "yyy": ["/fpc"]}]},

                {"/vrf": [{"xxx": [""], "yyy": ["/abcdefg"]}]},

                {"/lsp": [{"xxx": [""], "yyy": ["/abcdefg"]}]},

                {"/vpn": [{"xxx": [""], "yyy": ["/abcdefg"]}]},

                {"/fpc": [{"xxx": ["/abcdefg"], "yyy": [""]}]}

        ],

        "redisConfig": {"broker": "localhost: 6379", "db": 0}

}

在执行 UnMarshall 时,它会抛出无法解析的错误。


所以我决定首先以编程方式将所需的地图编组为 json,然后打印出来。


{"resourceType":{"/fpc":{"XXX":["/abcdefg"],"YYY":[]},

"/abcdefg":{"XXX":["/vrf","/lsp","/vpn"],"YYY":["/fpc"]},

"/abc":{"XXX":[],"YYY":["/abcdefg"]},

"/vpn":{"XXX":[],"YYY":["/abcdefg"]},

"/vrf":{"XXX":[],"YYY":["/abcdefg"]}},

"redisConfig":{"broker":"localhost:6349","db":"0"}}

现在在 json 文件中使用相同的格式并对其进行 UnMarshal 处理。它将很好地适合您根据最初生成 Json 所定义的类型。


查看完整回答
反对 回复 2022-05-05
  • 3 回答
  • 0 关注
  • 1542 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号