다음과 같은 방식으로 exec.Command 출력의 출력을 얻었습니다. 그 출력에서 ​​필요한 데이터를 얻고 싶습니다.

Oct 20 2020

여기 출력에서 ​​requestStatus Failed 부분 만있는 json 데이터 만 원합니다. 나머지 json 데이터는 각 업데이트를 재정의해야하며 삭제할 수 있습니다. pls는 필요한 데이터를 어떻게 얻을 수 있는지 제안 해 주시겠습니까? 소스 코드 : 내 소스 코드는 다음과 같습니다.

cmd := exec.Command(command, args...)
cmd.Dir = dir

var stdBuffer bytes.Buffer
mw := io.MultiWriter(os.Stdout, &stdBuffer)

cmd.Stdout = mw
cmd.Stderr = mw

// Execute the command
if err := cmd.Run(); err != nil {
    log.Panic(err)
}

log.Println(stdBuffer.String())

    
Output: this is how output looks for my input.

{
   "time": "10:26:03 AM",
   "requestId": 71795,
   "requestStatus": "ongoing",
   "requestMessage": "Waiting for response"
}
{
   "time": "10:26:08 AM",
   "requestId": 71795,
   "requestStatus": "ongoing",
   "requestMessage": "Waiting for response"
}
{
   "time": "10:26:13 AM",
   "requestId": 71795,
   "requestStatus": "ongoing",
   "requestMessage": "Waiting for response"
}
{
   "time": "10:26:14 AM",
   "requestId": 71795,
   "requestStatus": "failed",
   "requestMessage": {
      "ValidationResult": {
         "logs": {
            "Elements": null,
            "objectsErrors": null,
            "occurrencesErrors": null
         }
      }
    }
}

답변

icza Oct 20 2020 at 17:56

json.Unmarshal()출력 (여러 JSON 개체의 연결)과 같이 여러 (독립적 인) JSON 값을 포함하는 항목을 비 정렬 화 하는 데 사용할 수 없습니다 .

json.Decoder스트림에서 하나씩 여러 JSON 값 (객체)을 디코딩하는 데 사용 합니다.

예를 들면 :

dec := json.NewDecoder(strings.NewReader(output))

var m map[string]interface{}
for {
    if err := dec.Decode(&m); err != nil {
        if err == io.EOF {
            break
        }
        panic(err)
    }
    fmt.Println("Decoded:", m)
}

다음과 같이 출력됩니다 ( Go Playground 에서 시도해보세요 ).

Decoded: map[requestId:71795 requestMessage:Waiting for response requestStatus:ongoing time:10:26:03 AM]
Decoded: map[requestId:71795 requestMessage:Waiting for response requestStatus:ongoing time:10:26:08 AM]
Decoded: map[requestId:71795 requestMessage:Waiting for response requestStatus:ongoing time:10:26:13 AM]
Decoded: map[requestId:71795 requestMessage:map[ValidationResult:map[logs:map[Elements:<nil> objectsErrors:<nil> occurrencesErrors:<nil>]]] requestStatus:failed time:10:26:14 AM]

에서 콘텐츠를 디코딩하려면 stdBuffer다음으로 전달할 수 있습니다 json.NewDecoder().

dec := json.NewDecoder(&stdBuffer)

"failed"상태가 있는 객체 만 출력해야하는 경우 다음 if명령문을 사용하면됩니다 .

    if m["requestStatus"] == "failed" {
        fmt.Println("Decoded:", m)
    }

다음과 같이 출력됩니다 ( Go Playground 에서 시도해보세요 ).

Decoded: map[requestId:71795 requestMessage:map[ValidationResult:map[logs:map[Elements:<nil> objectsErrors:<nil> occurrencesErrors:<nil>]]] requestStatus:failed time:10:26:14 AM]