Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert string from interface to []string in golang?

Tags:

go

I'm parsing a JSON object which contains an array of strings :

var ii interface{}
json := "{\"aString\": [\"aaa_111\", \"bbb_222\"], \"whatever\":\"ccc\"}"

err := json.Unmarshal([]byte(json), &ii)
if err != nil {
    log.Fatal(err)
}
data := ii.(map[string]interface{})
fmt.Println(data["aString"]) // outputs: ["aaa_111" "bbb_222"]

I tried to convert data["aString"] to []string to be able to loop over it, but it fails :

 test := []string(data["aString"]).([]string)
 fmt.Println(test) // panic -> interface conversion: 
                   //          interface is string, not []string

How can I convert data["aString"] ?


edit:

I didn't express myself properly. If I print data, I have such map :

map[aString:["BBB-222","AAA-111"] whatever:ccc]

I want to loop over aString (to manipule each array entry). But I can't find how, because aString is type interface {} :

for i, v := range aString { // <-- fails
     // ...
     fmt.Println(i, v)
}

That's why I want to convert aString. I don't want to convert a string which looks like an array to an array.

like image 281
Jérôme Avatar asked May 19 '16 16:05

Jérôme


People also ask

How do you convert interface to string in Golang?

To convert interface to string in Go, use fmt. Sprint function, which gets the default string representation of any value. If you want to format an interface using a non-default format, use fmt. Sprintf with %v verb.

What is [] interface {} Golang?

interface{} means you can put value of any type, including your own custom type. All types in Go satisfy an empty interface ( interface{} is an empty interface). In your example, Msg field can have value of any type.

What is type assertion in Golang?

Type assertions in Golang provide access to the exact type of variable of an interface. If already the data type is present in the interface, then it will retrieve the actual data type value held by the interface. A type assertion takes an interface value and extracts from it a value of the specified explicit type.

What is a Golang interface?

Go language interfaces are different from other languages. In Go language, the interface is a custom type that is used to specify a set of one or more method signatures and the interface is abstract, so you are not allowed to create an instance of the interface.


1 Answers

I recommend you move away from this implementation in general. Your json may vary but you can easily use objects and avoid all this type unsafe nonsense.

Anyway, that conversion doesn't work because the types inside the slice are not string, they're also interface{}. You have to iterate the collection then do a type assertion on each item like so:

aInterface := data["aString"].([]interface{})
aString := make([]string, len(aInterface))
for i, v := range aInterface {
    aString[i] = v.(string)
}
like image 66
evanmcdonnal Avatar answered Oct 11 '22 06:10

evanmcdonnal