Golang encoding/json.NewDecoder() function example
package encoding/json
NewDecoder returns a new decoder that reads from r (1st parameter). The decoder introduces its own buffering and may read data from r beyond the JSON values requested.
Golang encoding/json.NewDecoder() function usage example
package main
import (
"encoding/json"
"fmt"
"strings"
"io"
)
func main() {
var jsonDataStream = `
{"Name":"Adam","Age":36,"Job":"CEO"}
{"Name":"Eve","Age":34,"Job":"CFO"}
{"Name":"Mike","Age":38,"Job":"COO"}
`
type Employee struct {
Name string
Age int
Job string
}
decoder := json.NewDecoder(strings.NewReader(jsonDataStream))
for {
var worker Employee
if err := decoder.Decode(&worker); err == io.EOF {
break
} else if err != nil {
fmt.Println(err)
}
fmt.Printf("%s | %d | %s\n", worker.Name, worker.Age, worker.Job)
}
}
Output :
Adam | 36 | CEO
Eve | 34 | CFO
Mike | 38 | COO
Reference :
Advertisement
Something interesting
Tutorials
+11k Golang : Get UDP client IP address and differentiate clients by port number
+6.6k Golang : Spell checking with ispell example
+19.5k Golang : Fix cannot download, $GOPATH not set error
+14.7k Golang : GUI with Qt and OpenCV to capture image from camera
+5.4k PHP : Hide PHP version information from curl
+13.7k Golang : Set image canvas or background to transparent
+5.4k Golang : Get FX sentiment from website example
+7.5k Golang : Example of custom handler for Gorilla's Path usage.
+35.4k Golang : Strip slashes from string example
+14.4k Golang : Simple word wrap or line breaking example
+17.3k Golang : Find file size(disk usage) with filepath.Walk