Golang string array to array object with json value

Issue

I have variable with data type string

string := "[{"type":"header","temp":{"data":"image"}},{"type":"body","temp":{"req":"text","msg":"test"}}]"

How to convert string to array with json value like

string := [{"type":"header","temp":{"data":"image"}},{"type":"body","temp":{"req":"text","msg":"test"}}]

Solution

You will need to define a mapper variable type with array []map[string]interface{}

s := "[{\"type\":\"header\",\"temp\":{\"data\":\"image\"}}, {\"type\":\"body\",\"temp\":{\"req\":\"text\",\"msg\":\"test\"}}]"
var dat []map[string]interface{}

if err := json.Unmarshal([]byte(s), &dat); err != nil {
    panic(err)
}

fmt.Printf("%v\n", dat)

Answered By – turboza

Answer Checked By – Katrina (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.