Search code examples
goresponsego-interface

How to convert the value inside an interface into a map in golang?


I am a complete newbie to GO.

My objective is to get the data inside item.Data and put them into a map so that I can access them as a key value pair.

As far as I understand an empty interface is as same as any type in Typescript.

Can you please share a snippet of how to do it in 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 A log search result entry

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: The data inside item.Data is a list of key value pair where each key could contain data inside another interface whose value is a string

Edit : Keys are dynamic

Github Link

Screenshot of interface containing data


Solution

  • First: do not use *interface{}, instead use interface{}.

    You can use type assertions to test the underlying type of Data and recursively descend if it is a map[string]interface{}:

    (You mentioned this is part of the SDK and cannot be changed, so the workaround is to dereference the 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
       }
    }