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
+8.6k Golang : How to convert a number to words
+7.7k Golang : Calculate Relative Strength Index(RSI) example
+11.8k Golang : Get the IPv4 and IPv6 addresses for a specific network interface
+4.7k Web : How to see your website from different countries?
+5k Golang : Detect sample rate, channels or latency with PortAudio
+15.5k Golang : Reset or rewind io.Reader or io.Writer
+4.1k Unix/Linux : How to get own IP address ?
+14.8k How to enable MariaDB/MySQL logs ?
+27.3k Golang : Save image to PNG, JPEG or GIF format.
+4.1k Golang : Handling image beyond OpenCV video capture boundary
+5.8k Golang : Handle sub domain with Gin
+6.4k Linux : How to install driver for 600Mbps Dual Band Wifi USB Adapter