如何解决我以以下方式获取exec.Command输出从该输出中,我想获取所需的数据
在这里,我只需要请求状态失败部分的json数据。剩余的json数据应在每次更新时覆盖/可以删除。您能否建议我如何获取仅需要的数据? 源代码:我的源代码看起来像这样。
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","requestMessage": "Waiting for response"
}
{
"time": "10:26:13 AM","requestMessage": "Waiting for response"
}
{
"time": "10:26:14 AM","requestStatus": "failed","requestMessage": {
"ValidationResult": {
"logs": {
"Elements": null,"objectsErrors": null,"occurrencesErrors": null
}
}
}
}
解决方法
您不能使用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]
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。