Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

golang convert array of interfaces to strings

I read JSON data from a remote source and convert it to a map. There's some array in the data of which I want to examine the string values. After converting I think m["t"] is an array of interfaces. fmt.Print converts this to printed text on the console but I cannot figure a way to do a simple string comparison like

if val[0] == "str-c" {fmt.Println("success")}

How do I iterate through that and do string comparisons?

package main

import (
    "fmt"
    "encoding/json"
)

func main() {
    var m map[string]interface{}
    sJSON := `{"k": "v", "t":["str-a","str-b","str-c"]}`
    _ = json.Unmarshal([]byte(sJSON),&m)

    // find out if one of the string values of "t" is "str-b"
    fmt.Println(m["t"]) 
}
like image 556
user208383 Avatar asked Mar 15 '23 01:03

user208383


1 Answers

m["t"] is of type interface{} and is the full array, if you wanted to get str-b it is at index one and you have to do some type assertion to get it as a string. Here's an example; https://play.golang.org/p/W7ZnMgicc7

If you want to check for it in the collection that would look like this;

package main

import (
    "fmt"
    "encoding/json"
)

func main() {
    var m map[string]interface{}
    sJSON := `{"k": "v", "t":["str-a","str-b","str-c"]}`
    _ = json.Unmarshal([]byte(sJSON),&m)

    // find out if one of the string values of "t" is "str-b"
    for _, v := range m["t"].([]interface{}) {
         if v.(string) == "str-b" {
              fmt.Println("match found!")
         }
    }
    //fmt.Println(m["t"].([]interface{})[1].(string)) 
}

https://play.golang.org/p/vo_90bKw92

If you want to avoid this 'unboxing' stuff, which I would recommend you do, you could instead define a struct to unmarshal into, itwould look like this;

type MyStruct struct {
     K string `json:"k"`
     T []string `json:"t"`
}

Then you can just range over T without any type assertions and do the compare, working example here; https://play.golang.org/p/ehPxOygGf5

like image 180
evanmcdonnal Avatar answered Mar 24 '23 10:03

evanmcdonnal