go - 如何将接口(interface)内的值转换为golang中的 map ?

标签 go response go-interface

我是 GO 的新手。
我的目标是获取 item.Data 中的数据并将它们放入 map 中,以便我可以将它们作为键值对进行访问。
据我了解,空接口(interface)与 Typescript 中的任何类型相同。
你能分享一下如何在goLang中做到这一点吗?

type SearchLogsResponse struct {

    // The underlying http response
    RawResponse *http.Response

    // A list of SearchResponse instances
    SearchResponse `presentIn:"body"`

    // For list pagination. When this header appears in the response, additional pages
    // of results remain. For important details about how pagination works, see
    // List Pagination (https://docs.cloud.oracle.com/iaas/Content/API/Concepts/usingapi.htm#nine).
    OpcNextPage *string `presentIn:"header" name:"opc-next-page"`

    // Unique Oracle-assigned identifier for the request. If you need to contact
    // Oracle about a particular request, please provide the request ID.
    OpcRequestId *string `presentIn:"header" name:"opc-request-id"`
}
//SearchResult 日志搜索结果条目
type SearchResult struct {

    // JSON blob containing the search entry with projected fields.
    Data *interface{} `mandatory:"true" json:"data"`
}


// SearchResponse Search response object.
type SearchResponse struct {
    Summary *SearchResultSummary `mandatory:"true" json:"summary"`

    // List of search results
    Results []SearchResult `mandatory:"false" json:"results"`

    // List of log field schema information.
    Fields []FieldInfo `mandatory:"false" json:"fields"`
}

res, err1 := o.loggingSearchClient.SearchLogs(ctx, request)
    for _, item := range res.Results {

            //TODO create a map string [string]

            // Put key value pairs from item into the above map




}
P.S:item.Data 中的数据是一个键值对列表,其中每个键可以包含另一个接口(interface)内的数据,其值是一个字符串
编辑:键是动态的
Github Link
Screenshot of interface containing data

最佳答案

第一:不要使用*interface{} , 而是使用 interface{} .
您可以使用类型断言来测试 Data 的基础类型如果是 map[string]interface{},则递归下降:
(您提到这是 SDK 的一部分,无法更改,因此解决方法是取消引用接口(interface))

if m, ok:=(*item.Data).(map[string]interface{}); ok {
   // m is a map[string]interface{}
   etag:=m["data.eTag"]
   // etag is an interface{}
   if str, ok:=etag.(string); ok {
      // str contains the string value
   }
}

关于go - 如何将接口(interface)内的值转换为golang中的 map ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63626304/

相关文章:

unit-testing - 如何使用 Go 的 moq 模拟 http.Handler?

转到接口(interface) : interface not implemented even though it is

go - 获取 "implicit assignment of unexported field"

postgresql - 使用 SQL 从 Docker 迁移数据库不起作用

go - 你可以在一个目录中有多个 Go 源文件吗?

python - 在django中更新cookie而不重置过期时间

mysql - 如何处理客户端向服务器发出的多个请求

java - 企业 Web 应用程序中 JSP 页面加载的性能问题

go - 错误: cannot load values. yaml:将YAML转换为JSON时发生错误:yaml:第**行:找不到预期的 key

go - 类型转换接口(interface) slice