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
+13.4k Golang : Intercept Ctrl-C interrupt or kill signal and determine the signal type
+8k Golang : Turn string or text file into slice example
+10.8k Golang : Exit, terminating or aborting a program
+3.4k Golang : How to pass data between controllers with JSON Web Token
+6.7k Golang : How to check if input string is a word?
+6.9k Golang : Convert word to its plural form example
+4.1k PHP : Hide PHP version information from curl
+5.5k Swift : substringWithRange() function example
+28.7k error: trying to remove "yum", which is protected
+19.7k Golang : Match strings by wildcard patterns with filepath.Match() function
+6k Golang : Command line ticker to show work in progress
+20.9k Golang : Calculate time different