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
+40.1k Golang : Convert string to array/slice
+15.7k Golang : XML to JSON example
+10.9k Golang : Encrypt and decrypt data with x509 crypto
+15k Golang : Check if a string contains multiple sub-strings in []string?
+6.9k Golang : How to feed or take banana with Gorilla Web Toolkit Session package
+17.1k Golang : Read binary file into memory
+13.6k nginx: [emerg] unknown directive "ssl"
+19.7k Golang : Get password from console input without echo or masked
+3.7k JavaScript : Rounding number to decimal formats to display currency
+18.8k Golang : Count number of digits from given integer value
+8.5k Golang : How to check if a website is served via HTTPS
+18.4k Golang : Reset or rewind io.Reader or io.Writer