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
+10.1k Golang : Identifying Golang HTTP client request
+29.5k Golang : Login(Authenticate) with Facebook example
+5.4k Golang : Get S3 or CloudFront object or file information
+6.1k Golang : How to write backslash in string?
+18k Golang : Get all upper case or lower case characters from string example
+12.3k Golang : Get month name from date example
+8.5k Linux/Unix : fatal: the Postfix mail system is already running
+18.7k Golang : convert int to string
+9.4k Golang : Find the length of big.Int variable example
+14.5k Golang : Overwrite previous output with count down timer
+35.1k Golang : Upload and download file to/from AWS S3
+12.8k Golang : Convert int(year) to time.Time type