How to reads and decodes JSON values from an input stream?
This example uses a Decoder to decode a stream of distinct JSON values.
Example
package main
import (
"encoding/json"
"fmt"
"io"
"log"
"strings"
)
func main() {
const jsonStream = `
{"Name": "John", "City": "Bangkok", "Salary": 54552}
{"Name": "Mark", "City": "London", "Salary": 98545}
{"Name": "Sandy", "City": "Paris", "Salary": 34534}
{"Name": "Holard", "City": "Tokyo", "Salary": 34534}
`
type Employee struct {
Name, City string
Salary int32
}
dec := json.NewDecoder(strings.NewReader(jsonStream))
for {
var emp Employee
if err := dec.Decode(&emp); err == io.EOF {
break
} else if err != nil {
log.Fatal(err)
}
fmt.Printf("%s: %s: %d\n", emp.Name, emp.City, emp.Salary)
}
}
Output
John: Bangkok: 54552
Mark: London: 98545
Sandy: Paris: 34534
Holard: Tokyo: 34534
Most Helpful This Week
Create and Print Multi Dimensional Slice in Golang
Replace numbers by zero from string
How to use a mutex to define critical sections of code and fix race conditions?
Find element in a slice and move it to first position?
How to trim leading and trailing white spaces of a string in Golang?
How to print struct variables data in Golang?