kingSlayer kingSlayer - 3 months ago 7
JSON Question

Parse array in Golang

Simple question: how to parse a string (which is an array) in Go using json package?

type JsonType struct{
Array []string
}

func main(){
dataJson = `["1","2","3"]`
arr := JsonType{}
unmarshaled := json.Unmarshal([]byte(dataJson), &arr.Array)
log.Printf("Unmarshaled: %v", unmarshaled)
}

Answer

The return value of Unmarshal is an err, and this is what you are printing out:

// wrong, unmarshaled is actually the error
unmarshaled := json.Unmarshal([]byte(dataJson), &arr)

You can get rid of the JsonType as well and just use a slice:

package main

import (
    "encoding/json"
    "log"
)

func main() {
    dataJson := `["1","2","3"]`
    var arr []string
    _ = json.Unmarshal([]byte(dataJson), &arr)
    log.Printf("Unmarshaled: %v", arr)
}

// prints out:
// 2009/11/10 23:00:00 Unmarshaled: [1 2 3]

Code on play: https://play.golang.org/p/GNWlylavam