问题
Here from output I want only json data with requestStatus Failed part only. remaining json data should be override each update/can be deleted. could you pls suggest me how can I get data which is only required. source Code: my source code looks like this.
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
}
}
}
}
回答1:
You can't use json.Unmarshal() to unmarshal something that contains multiple (independent) JSON values, such as your output (which is a concatenation of multiple JSON objects).
Use json.Decoder to decode multiple JSON values (objects) from a stream one-by-one.
For example:
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)
}
This will output (try it on the 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]
To decode content from your stdBuffer
, you may pass that to json.NewDecoder():
dec := json.NewDecoder(&stdBuffer)
If you only need to output the object with "failed"
status, simply use an if
statement:
if m["requestStatus"] == "failed" {
fmt.Println("Decoded:", m)
}
This will only output (try it on the 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]
来源:https://stackoverflow.com/questions/64443414/i-was-getting-output-of-exec-command-output-in-the-following-manner-from-that-o