您好,我正在尝试将 kinesis firehose 与 S3 一起使用。我尝试读取那些 s3 文件。我正在使用 GO 来阅读它。
但是,我无法解析 JSON,因为这些值只是附加的,没有任何分隔符。
这是文件的示例(请注意,原始输入是相互附加的,为了格式化目的,我用换行符将它们分开):
{"ticker_symbol":"PLM","sector":"FINANCIAL","change":-0.16,"price":19.99}
{"ticker_symbol":"AZL","sector":"HEALTHCARE","change":-0.78,"price":16.51}
{"ticker_symbol":"IOP","sector":"TECHNOLOGY","change":-1.98,"price":121.88}
{"ticker_symbol":"VVY","sector":"HEALTHCARE","change":-0.56,"price":47.62}
{"ticker_symbol":"BFH","sector":"RETAIL","change":0.74,"price":16.61}
{"ticker_symbol":"WAS","sector":"RETAIL","change":-0.6,"price":16.72}
我的问题是,如何在 Go 中解析它?我能想到的一个解决方案是将它们分割为 }{
并再次附加它们。但它非常hackish。
或者 kinesis firehose 是否提供分隔符?
------更新------
目前我已经实现了将所有 }{
替换为 },{
的解决方案,然后在开头添加 [
和 ]
在最后。然后解析它。
但是我仍在寻找替代方案,因为此解决方案会限制 json 对象内容中的任何 }{
最佳答案
创建一个简单的结构来解码批量传入的 json。因此,每个批处理 json 都会被解码到一个 json 对象中。然后创建一个结构体 slice ,将解析后的 json 附加到该 slice 中。这会将结果 json 全部附加到结构 slice 中。
package main
import (
"encoding/json"
"fmt"
)
type Ticker struct {
TickerSymbol string `json:"ticker_symbol"`
Sector string `json:"sector"`
Change float64 `json:"change"`
Price float64 `json:"price"`
}
var jsonBytes = []byte(`{"ticker_symbol":"PLM","sector":"FINANCIAL","change":-0.16,"price":19.99}`)
func main() {
var singleResult Ticker
var result []Ticker
if err := json.Unmarshal(jsonBytes, &singleResult); err != nil {
fmt.Println(err)
}
if len(result) == 0 {
result = append(result, singleResult)
}
fmt.Printf("%+v", result)
}
已编辑:
如果数据批量传入,其中包含相互附加的 json 对象,那么您可以使用正则表达式将 }
替换为 },
,然后修剪最右边,
将有效的 json 对象数组制作为:
package main
import (
"fmt"
"regexp"
"strings"
)
type Ticker struct {
TickerSymbol string `json:"ticker_symbol"`
Sector string `json:"sector"`
Change float64 `json:"change"`
Price float64 `json:"price"`
}
var str = `{"ticker_symbol":"PLM","sector":"FINANCIAL","change":-0.16,"price":19.99}
{"ticker_symbol":"AZL","sector":"HEALTHCARE","change":-0.78,"price":16.51}
{"ticker_symbol":"IOP","sector":"TECHNOLOGY","change":-1.98,"price":121.88}
{"ticker_symbol":"VVY","sector":"HEALTHCARE","change":-0.56,"price":47.62}
{"ticker_symbol":"BFH","sector":"RETAIL","change":0.74,"price":16.61}
{"ticker_symbol":"WAS","sector":"RETAIL","change":-0.6,"price":16.72}`
func main() {
r := regexp.MustCompile("}")
output := strings.TrimRight(r.ReplaceAllString(str, "},"), ",")
output = fmt.Sprintf("[%s]", output)
fmt.Println(output)
}
使用 r := regexp.MustCompile("}")
将帮助您不必担心 }{
之间的空格会干扰替换字符串。因此,只需将 }
替换为 },
,然后向右修剪即可。
另外,我使用 MustCompile 的原因是:
When creating constants with regular expressions you can use the MustCompile variation of Compile. A plain Compile won’t work for constants because it has 2 return values.
在 Go playground 上进行 json 解析的完整工作代码
关于json - 从 kinesis firehose 解析 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52638176/