Convert a string to an array in Go

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

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 -->

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

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 (
	&quot;encoding/json&quot;
	&quot;fmt&quot;
)

type Data struct {
    Name string
	Foo []string `json:&quot;foo&quot;`
}

func main() {
    // Unmarshall to slice
	var data []Data

    // Your string with list of objects
	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;]}]`
    
	err := json.Unmarshal([]byte(input), &amp;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.

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:

确定