여러 json 객체가있는 unmarshal json 파일 (유효한 json 파일이 아님) [중복]
Nov 20 2020
다음 내용이 포함 된 json 파일 (file.json)이 있습니다.
file.json :
{"job": "developer"}
{"job": "taxi driver"}
{"job": "police"}
파일 내용은 위와 동일합니다 (유효한 json 파일이 아님).
내 코드에서 데이터를 사용하고 싶지만 Unmarshal 수 없습니다.
답변
Зелёный Nov 20 2020 at 16:00
문자열을 한 줄씩 읽고 비 정렬화할 수 있습니다.
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}
예
4 icza Nov 20 2020 at 15:55
당신이 가진 것은 단일 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 개체가있는 경우에도 작동합니다.
관련 참조 : 다음과 같은 방식으로 exec.Command 출력의 출력을 얻었습니다. 그 출력에서 필요한 데이터를 얻고 싶습니다.