5

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"]) 
}

1 Answer 1

9

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.