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