英文:
Convert a string to an array in Go
问题
在Go语言中,我有以下字符串:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-html -->
["item1", "item2", "item3"]
<!-- end snippet -->
我想将这个字符串转换为包含每个项的列表。有什么最好的方法可以实现这个?抱歉,我还在学习Go语言,但是找不到类似的信息。
英文:
So in Go I have the following string
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-html -->
["item1", "item2", "item3"]
<!-- end snippet -->
I want to turn this string into a list containing each items. What is the best way to go about this? Sorry I am still learning Go but couldn't find similar info on this
答案1
得分: 1
如果你的字符串是JSON(如注释所示),其中包含相同类型的对象的顶级列表,你可以使用标准库中的encoding/json
来解析并将其简单地解组为你的Go结构类型的切片,代码如下:
package main
import (
"encoding/json"
"fmt"
)
type Data struct {
Name string
Foo []string `json:"foo"`
}
func main() {
// 解组为切片
var data []Data
// 包含对象列表的字符串
input := `[{"name": "first", "foo":["item1", "item2", "item3"]}, {"name": "second", "foo":["item5", "item6"]}]`
err := json.Unmarshal([]byte(input), &data)
if err != nil {
panic(err)
}
fmt.Println(data)
}
我建议阅读JSON and Go,该文章详细解释了如何在Go中读取JSON。
英文:
If your string is JSON (as comments suggest) that has top-level list of objects of same type; you can use encoding/json
from standard library to parse and simply unmarshal it into a slice of your Go struct type like this:
package main
import (
"encoding/json"
"fmt"
)
type Data struct {
Name string
Foo []string `json:"foo"`
}
func main() {
// Unmarshall to slice
var data []Data
// Your string with list of objects
input := `[{"name": "first", "foo":["item1", "item2", "item3"]}, {"name": "second", "foo":["item5", "item6"]}]`
err := json.Unmarshal([]byte(input), &data)
if err != nil {
panic(err)
}
fmt.Println(data)
}
I recommend reading JSON and Go which pretty much explains how to read JSON and in Go.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论