-3

So in Go I have the following string

["item1", "item2", "item3"]

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
  • The string is Json, the string is an array of json items, and I want to turn it into a go mapping of strings to interfaces. Commented Jun 14, 2021 at 1:39

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Sorry I didn't explain enough, its a string that is a json array. So an example would be "[{"object1" : data}, {"object2" : data} ]"
I see, I updated my answer. You should really reword the question so it reflects that.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.