If the structure of your JSON is not well defined and can change, that's the way to go:
import (
"fmt"
"encoding/json"
)
func main() {
var b = []byte(`{"a":"b", "c":1, "d": ["e", "f"]}`)
var j map[string]interface{}
err := json.Unmarshal(b, &j)
if (err != nil) {
return
}
printJson(j)
}
func printJson(j map[string]interface{}) {
for k, v := range j {
fmt.Printf("%v %v
", k, v)
}
}
If your JSON is well defined, though, you can unmarshal it into struct, which is usually better:
import (
"fmt"
"encoding/json"
)
type Message struct {
A string
C int
D []string
}
func main() {
var b = []byte(`{"a":"b", "c":1, "d": ["e", "f"]}`)
var j Message
err := json.Unmarshal(b, &j)
if (err != nil) {
return
}
printJson(j)
}
func printJson(j Message) {
fmt.Printf("A %v
", j.A)
fmt.Printf("C %v
", j.C)
fmt.Printf("D %v
", j.D)
}
You can play with later code here: https://play.golang.org/p/wDPy4m2x2_t