解组 json 具有多个 json 对象的文件(无效的 json 文件)
unmarshal json file with multiple json object (not valid json file)
我有一个 json 文件 (file.json),其中包含以下内容:
file.json:
{"job": "developer"}
{"job": "taxi driver"}
{"job": "police"}
文件内容与上面完全相同(无效json文件)
我想在我的代码中使用数据,但我无法对此进行解组
您拥有的不是单个 JSON 对象,而是一系列(不相关的)JSON 对象。您不能使用 json.Unmarshal()
解组包含多个(独立)JSON 值的内容。
使用 json.Decoder
逐个解码源中的多个 JSON 值(对象)。
例如:
func main() {
f := strings.NewReader(file)
dec := json.NewDecoder(f)
for {
var job struct {
Job string `json:"job"`
}
if err := dec.Decode(&job); err != nil {
if err == io.EOF {
break
}
panic(err)
}
fmt.Printf("Decoded: %+v\n", job)
}
}
const file = `{"job": "developer"}
{"job": "taxi driver"}
{"job": "police"}`
哪些输出(在 Go Playground 上尝试):
Decoded: {Job:developer}
Decoded: {Job:taxi driver}
Decoded: {Job:police}
即使您的 JSON 对象在源文件中占据多行,或者同一行中有多个 JSON 对象,此解决方案也有效。
查看相关:I was getting output of exec.Command output in the following manner. from that output I want to get data which I needed
您可以逐行读取字符串并将其解组:
package main
import (
"bufio"
"encoding/json"
"fmt"
"strings"
)
type j struct {
Job string `json:"job"`
}
func main() {
payload := strings.NewReader(`{"job": "developer"}
{"job": "taxi driver"}
{"job": "police"}`)
fscanner := bufio.NewScanner(payload)
for fscanner.Scan() {
var job j
err := json.Unmarshal(fscanner.Bytes(), &job)
if err != nil {
fmt.Printf("%s", err)
continue
}
fmt.Printf("JOB %+v\n", job)
}
}
输出:
JOB {Job:developer}
JOB {Job:taxi driver}
JOB {Job:police}
我有一个 json 文件 (file.json),其中包含以下内容:
file.json:
{"job": "developer"}
{"job": "taxi driver"}
{"job": "police"}
文件内容与上面完全相同(无效json文件)
我想在我的代码中使用数据,但我无法对此进行解组
您拥有的不是单个 JSON 对象,而是一系列(不相关的)JSON 对象。您不能使用 json.Unmarshal()
解组包含多个(独立)JSON 值的内容。
使用 json.Decoder
逐个解码源中的多个 JSON 值(对象)。
例如:
func main() {
f := strings.NewReader(file)
dec := json.NewDecoder(f)
for {
var job struct {
Job string `json:"job"`
}
if err := dec.Decode(&job); err != nil {
if err == io.EOF {
break
}
panic(err)
}
fmt.Printf("Decoded: %+v\n", job)
}
}
const file = `{"job": "developer"}
{"job": "taxi driver"}
{"job": "police"}`
哪些输出(在 Go Playground 上尝试):
Decoded: {Job:developer}
Decoded: {Job:taxi driver}
Decoded: {Job:police}
即使您的 JSON 对象在源文件中占据多行,或者同一行中有多个 JSON 对象,此解决方案也有效。
查看相关:I was getting output of exec.Command output in the following manner. from that output I want to get data which I needed
您可以逐行读取字符串并将其解组:
package main
import (
"bufio"
"encoding/json"
"fmt"
"strings"
)
type j struct {
Job string `json:"job"`
}
func main() {
payload := strings.NewReader(`{"job": "developer"}
{"job": "taxi driver"}
{"job": "police"}`)
fscanner := bufio.NewScanner(payload)
for fscanner.Scan() {
var job j
err := json.Unmarshal(fscanner.Bytes(), &job)
if err != nil {
fmt.Printf("%s", err)
continue
}
fmt.Printf("JOB %+v\n", job)
}
}
输出:
JOB {Job:developer}
JOB {Job:taxi driver}
JOB {Job:police}