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
Get Year, Month, Day, Hour, Min and Second from a specified date
How to Draw a rectangle in Golang?
How to trim leading and trailing white spaces of a string in Golang?
How to write backslash in Golang string?
Golang Read Write Create and Delete text file
How to use a mutex to define critical sections of code and fix race conditions?
Regular expression to extract filename from given path in Golang
Convert Float32 to Float64 and Float64 to Float32
How to remove symbols from a string in Golang?
Example: How to use TeeReader from IO Package in Golang?