将json文件与多个json对象解组(无效的json文件)



我有一个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: %+vn", job)
}
}
const file = `{"job": "developer"}
{"job": "taxi driver"}
{"job": "police"}`

哪些输出(在Go Playground上尝试(:

Decoded: {Job:developer}
Decoded: {Job:taxi driver}
Decoded: {Job:police}

即使JSON对象在源文件中占据多行,或者在同一行中有多个JSON对象,该解决方案也能工作。

参见相关内容:我得到了exec的输出。按以下方式输出命令。我想从输出中获得我需要的数据

您可以逐行读取字符串并对其进行解组:

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 %+vn", job)
}
}

输出:

JOB {Job:developer}
JOB {Job:taxi driver}
JOB {Job:police}

示例

最新更新