希望这能回答你的问题。注释出来的部分是用来逐个解码所有对象的,因此你甚至可以优化它,使多个goroutine可以并发地进行解码。
包主
import (
"encoding/json"
"fmt"
"log"
"os"
)
type jsonStore struct {
Name string
Age int
}
func main() {
file, err := os.Open("text.json")
if err != nil {
log.Println("Can't read file")
}
defer file.Close()
// NewDecoder that reads from file (Recommended when handling big files)
// It doesn't keeps the whole in memory, and hence use less resources
decoder := json.NewDecoder(file)
var data jsonStore
// Reads the array open bracket
decoder.Token()
// Decode reads the next JSON-encoded value from its input and stores it
decoder.Decode(&data)
// Prints the first single JSON object
fmt.Printf("Name: %#v, Age: %#v\n", data.Name, data.Age)
/*
// If you want to read all the objects one by one
var dataArr []jsonStore
// Reads the array open bracket
decoder.Token()
// Appends decoded object to dataArr until every object gets parsed
for decoder.More() {
decoder.Decode(&data)
dataArr = append(dataArr, data)
}
*/
}
产量
Name: "abc", Age: 10