嗨,我正在尝试用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中解析它?我能想到的一个解决方案是将它们拆分为}{,然后再追加它们。但还是挺讨厌的。
还是动力消防软管提供定界符?
------UPDATE------
目前,我已经实现了这个解决方案,将所有}{替换为},{,然后在开头添加[,最后添加]。那就解析它。
但是,我仍然在寻找替代方案,因为该解决方案将限制json对象内容中的任何}{。
发布于 2018-10-04 03:08:43
创建一个简单的结构来解组即将出现的json。因此,每个批处理json都被解组到一个json对象中。然后创建一个结构片段,将解析的json附加到切片中。这将将您的结果json全部添加到结构片中。
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对象,则可以使用regex表达式替换},然后将大多数,修剪成有效的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的另一个原因是:
在使用正则表达式创建常量时,可以使用编译的MustCompile变体。普通编译不适用于常量,因为它有两个返回值。
在去操场上使用json解析的完整工作代码
https://stackoverflow.com/questions/52638176
复制相似问题