3

I am looking for an answer in internet but it no one that fit my needs.

I have a string in the following format:

"[2,15,23]"

and i am trying to convert it in this format:

[2,15,23]

I need the type after the convertion to change to []int. I need to convert it because i want to use it later to make an interface type to use it in a sql query as param.

Is there any way to convert it?

Thanks

2

3 Answers 3

7

A better way using json.Unmarshal:

func main() {
    str := "[2,15,23]"
    var ints []int
    err := json.Unmarshal([]byte(str), &ints)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("%v", ints)
}
Sign up to request clarification or add additional context in comments.

Comments

1

This is slightly hackish but you could treat it like a csv:

import (
    "encoding/csv"
    "strings"
)

in := `"[2,15,23]"`
r := csv.NewReader(strings.NewReader(in))

records, err := r.ReadAll()

1 Comment

ReadAll() returns [][]string, not []int as asked. Additional conversion from string to int is required.
1

Here is a working example if you haven't figured it out based on the comments suggesting that you use json.Unmarshal

Playground link

package main

import (
    "fmt"
    "log"
    "encoding/json"
)

func main() {
    str := "[2,15,23]"
    ints, err := convertToIntSlice(str)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("%v", ints)
}

type IntSlice struct {
    Ints []int
}

func convertToIntSlice(s string) ([]int, error) {
    a := &IntSlice{}
    err := json.Unmarshal([]byte(`{"Ints":`+s+"}"), a)
    return a.Ints, err
}

1 Comment

You don't need all this overhead of declaring a type, you can Unmarshal directly in an int slice: play.golang.org/p/3VgfnPo7Hz

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.