当前位置: > > > > 转换具有单个混合数据类型数组的单个字符串
来源:stackoverflow
2024-04-19 16:27:36
0浏览
收藏
本篇文章给大家分享《转换具有单个混合数据类型数组的单个字符串》,覆盖了Golang的常见基础知识,其实一个语言的全部知识点一篇文章是不可能说完的,但希望通过这些问题,让读者对自己的掌握程度有一定的认识(B 数),从而弥补自己的不足,更好的掌握它。
问题内容
如何转换其中包含单个字符串数组的单个字符串。
func main() { stringarrayinstring := "[\"hello\",\"hai\",\"how are you!\"]" //single string which has string array in it fmt.println(stringarrayinstring) // code to convert to the string array // convertedstring }
输出必须是这样的
convertedstring[0] = "hello" convertedstring[1] = "hai" convertedstring[2] = "how are you!"
如果上面的输入字符串有int、string、json类型等混合数据类型是否可以 例如
stringArrayInString := "[\"Hello\",\"{\"msg\":\"Hai\"}\",123]" //after converting convertedString[0] = "Hello" convertedString[1] = "{\"msg\":\"Hai\"}" convertedString[2] = 123
解决方案
您拥有的字符串数组是一个有效的 json 数组,因此您可以执行以下操作:
var convertedstring []string json.unmarshal([]byte(str),&convertedstring)
如果该数组中有多种数据类型,则可以使用字符串数组来实现,您需要一个 interface{} 数组:
var convertedData []interface{} json.Unmarshal([]byte(str),&convertedData)
然后您需要检查该数组中各个元素的类型以找出它们是什么。
本篇关于《转换具有单个混合数据类型数组的单个字符串》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于Golang的相关知识,请关注公众号!