Convert a string to an array in Go

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

Convert a string to an array in Go

问题

在Go语言中,我有以下字符串:

  1. <!-- begin snippet: js hide: false console: true babel: false -->
  2. <!-- language: lang-html -->
  3. ["item1", "item2", "item3"]
  4. <!-- end snippet -->

我想将这个字符串转换为包含每个项的列表。有什么最好的方法可以实现这个?抱歉,我还在学习Go语言,但是找不到类似的信息。

英文:

So in Go I have the following string

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-html -->

  1. [&quot;item1&quot;, &quot;item2&quot;, &quot;item3&quot;]

<!-- 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结构类型的切片,代码如下:

  1. package main
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. )
  6. type Data struct {
  7. Name string
  8. Foo []string `json:"foo"`
  9. }
  10. func main() {
  11. // 解组为切片
  12. var data []Data
  13. // 包含对象列表的字符串
  14. input := `[{"name": "first", "foo":["item1", "item2", "item3"]}, {"name": "second", "foo":["item5", "item6"]}]`
  15. err := json.Unmarshal([]byte(input), &data)
  16. if err != nil {
  17. panic(err)
  18. }
  19. fmt.Println(data)
  20. }

我建议阅读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:

  1. package main
  2. import (
  3. &quot;encoding/json&quot;
  4. &quot;fmt&quot;
  5. )
  6. type Data struct {
  7. Name string
  8. Foo []string `json:&quot;foo&quot;`
  9. }
  10. func main() {
  11. // Unmarshall to slice
  12. var data []Data
  13. // Your string with list of objects
  14. input := `[{&quot;name&quot;: &quot;first&quot;, &quot;foo&quot;:[&quot;item1&quot;, &quot;item2&quot;, &quot;item3&quot;]}, {&quot;name&quot;: &quot;second&quot;, &quot;foo&quot;:[&quot;item5&quot;, &quot;item6&quot;]}]`
  15. err := json.Unmarshal([]byte(input), &amp;data)
  16. if err != nil {
  17. panic(err)
  18. }
  19. fmt.Println(data)
  20. }

I recommend reading JSON and Go which pretty much explains how to read JSON and in Go.

huangapple
  • 本文由 发表于 2021年6月14日 09:06:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/67963767.html
匿名

发表评论

匿名网友

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

确定