2 回答

TA貢獻(xiàn)1789條經(jīng)驗(yàn) 獲得超10個(gè)贊
希望這能回答您的問題。注釋掉的部分是用于一一解碼所有對(duì)象,因此您甚至可以對(duì)其進(jìn)行優(yōu)化,以便多個(gè) goroutine 可以同時(shí)進(jìn)行解碼。
包主
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

TA貢獻(xiàn)1836條經(jīng)驗(yàn) 獲得超5個(gè)贊
您可以打開該文件,并使用 json.Decoder 開始讀取該文件。讀取數(shù)組第一個(gè)元素的代碼草圖如下所示:
decoder:=json.NewDecoder(f)
t,err:=decoder.Token()
tok, ok:=t.(json.Delim)
if ok {
if tok=='[' {
for decoder.More() {
decoder.Decode(&oneEntry)
}
}
}
您需要添加錯(cuò)誤處理。
- 2 回答
- 0 關(guān)注
- 224 瀏覽
添加回答
舉報(bào)