douzhuozhu9544
2015-11-25 18:40
浏览 355

golang将接口数组转换为字符串

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条回答 默认 最新

  • doudui1850 2015-11-25 18:50
    已采纳

    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

    已采纳该答案
    打赏 评论

相关推荐 更多相似问题