golang convert array of interfaces to strings

huangapple go评论86阅读模式
英文:

golang convert array of interfaces to strings

问题

我从远程源读取JSON数据并将其转换为映射。数据中有一些数组,我想检查字符串值。在转换后,我认为m["t"]是一个接口数组。fmt.Print将其转换为在控制台上打印的文本,但我无法找到一种简单的方法来进行字符串比较,例如:

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

如何遍历该数组并进行字符串比较?

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)
	
	// 找出"t"的字符串值中是否有"str-b"
	tArray := m["t"].([]interface{})
	for _, val := range tArray {
		if val.(string) == "str-b" {
			fmt.Println("success")
			break
		}
	}
}

以上是你提供的代码的修改版,可以遍历数组并进行字符串比较。

英文:

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

得分: 9

m["t"]的类型是interface{},它是完整的数组。如果你想获取str-b,它位于索引为1的位置,你需要进行一些类型断言将其转换为字符串。这里有一个示例:https://play.golang.org/p/W7ZnMgicc7

如果你想在集合中检查它,可以这样做:

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)

    // 判断 "t" 中是否有字符串值为 "str-b"
    for _, v := range m["t"].([]interface{}) {
         if v.(string) == "str-b" {
              fmt.Println("找到匹配!")
         }
    }
    //fmt.Println(m["t"].([]interface{})[1].(string)) 
}

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

如果你想避免这种“拆箱”操作,我建议你定义一个结构体进行解组,代码如下:

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

然后你可以直接遍历T,无需进行任何类型断言并进行比较。这里有一个可运行的示例:https://play.golang.org/p/ehPxOygGf5

英文:

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

huangapple
  • 本文由 发表于 2015年11月26日 02:40:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/33924131.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定