我正在使用 Go 中的 json 结构输入流。我在我的 stdin 上接收到来自另一个应用程序的输入流,但我无法更改通信协议(protocol)。
我遇到的问题是每个 json 结构都以非 json 字符串行终止:“end”(不带引号)。
我正在使用 Golang 编码器/json 包来解码我从标准输入接收到的 json。问题是解码器在我第二次使用消息调用它时产生错误:“无效字符‘e’寻找值的开头”。
当然,问题是“end”字符串不是 json 编码的。我想知道如何让 Go 的 json 解码器跳过这个字符串?
一些示例输入:
{"command": "ack", "id": "1231231"}
end
{"command": "fail", "id": "1231231"}
end
{
"command": "log",
// the message to log
"msg": "hello world!"
}
end
我尝试过的事情:
- 我声明:endStr := make([]byte, 10)
- 我尝试使用 fmt.Fscanf(os.Stdin, "%s", endStr) 来读取字符串,但未读取任何数据。
- 我试过使用 os.Stdin.Read(endStr),但它也没有返回任何数据。
- 在我读取第一个 json 结构后,dec.Buffered() 返回一个包含“end”字符串的 io.Reader,但我不知道如何让解码器跳过它。
如有任何帮助,我们将不胜感激。
最佳答案
所以我能想到的最好的解决方案是:
- 放弃 json 解码器,
- 从标准输入中读取一个 byte slice ,
- 修剪 slice 以排除 ("\nend\n") 字符串
- 将修剪后的 slice 传递给 json Unmarshaller
我必须写的代码:
// Create a buffer to hold the stream data
data := make([]byte, 5000)
// Read data from stdin in a loop
for {
_, err = os.Stdin.Read(data)
if err != nil {
panic(err)
}
index := bytes.Index(data, []byte("\n"))
data = data[:index]
var myStruct MyStruct
err = json.Unmarshal(data, &myStruct)
if err != nil {
panic(err)
}
//(Do something with myStruct)
}
关于json - 在 Go 中过滤 json 流中的非 json 内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17676367/