英文:
How to parse strings of json object seperated by comma but not enclosed by array
问题
在下面的示例中,由警报规则创建的elasticsearch文档中,hits下包含了3个逗号分隔的json对象字符串,但它们没有包含在一个数组[]中,因此在Go中无法解析它们。
有人可以帮我解析hits文档吗?
[map[_id:2s3kfXoB2vuM1J-EwpE7 _index:alert-X _score:%!s(float64=1)
_source:
map[@timestamp:2021-07-06T22:16:21.818Z
alert_name:alert events login
hits:
{"_index":".ds-logs-events-2021.06.30-000005","_type":"_doc","_id":"S83kfXoB2vuM1J-Eo4_v", ...
{"_index":".ds-logs-events-2021.06.30-000005","_type":"_doc","_id":"Ss3kfXoB2vuM1J-Eo4_v",...
{"_index":".ds-logs-events-2021.06.30-000005","_type":"_doc","_id":"N83kfXoB2vuM1J-EiI2l",...
rule_id:cfb85000-db0e-11eb-83e0-bb11d01642c7
]
模型
type Alert struct {
Alert string `json:"alert_name"`
Hits []*Event `json:"hits"`
}
type Event struct {
Model string
Action string
}
参考官方示例
使用官方的go-elasticsearch和easyjson
英文:
In the below sample elasticsearch doument created by the alerting rule, contains 3 comma seperated string of json objects under hits but they are NOT contained in an array [], so in Go unable to parse them.
Can someone help me parse the hits documents
[map[_id:2s3kfXoB2vuM1J-EwpE7 _index:alert-X _score:%!s(float64=1)
_source:
map[@timestamp:2021-07-06T22:16:21.818Z
alert_name:alert events login
hits:
{"_index":".ds-logs-events-2021.06.30-000005","_type":"_doc","_id":"S83kfXoB2vuM1J-Eo4_v", ...
{"_index":".ds-logs-events-2021.06.30-000005","_type":"_doc","_id":"Ss3kfXoB2vuM1J-Eo4_v",...
{"_index":".ds-logs-events-2021.06.30-000005","_type":"_doc","_id":"N83kfXoB2vuM1J-EiI2l",...
rule_id:cfb85000-db0e-11eb-83e0-bb11d01642c7
]
Model
type Alert struct {
Alert string `json:"alert_name"`
Hits []*Event `json:"hits"`
}
type Event struct {
Model string
Action string
}
Following offical example
Using official go-elasticsearch and easyjson
答案1
得分: 1
将json字符串与数组块连接起来,并成功解组它。
hitsArray := "[" + alert.Source.Hits + "]"
var hits []model.AlertHits
json.Unmarshal([]byte(hitsArray), &hits)
for _, hit := range hits {
log.Printf("hit %s action %s", hit.ID, hit.Source.Message.Action)
}
model.go
type AlertHits struct {
ID string `json:"_id"`
Source Event `json:"_source"`
}
type Event struct {
Message Message `json:"message"`
}
type Message struct {
Action string `json:"action"`
Model string `json:"model"`
}
英文:
Concatenated the json string with the array block and was able to Unmarshal it
hitsArray := "[" + alert.Source.Hits + "]"
var hits []model.AlertHits
json.Unmarshal([]byte(hitsArray), &hits)
for _, hit := range hits {
log.Printf("hit %s action %s", hit.ID, hit.Source.Message.Action)
}
model.go
type AlertHits struct {
ID string `json:"_id"`
Source Event `json:"_source"`
}
type Event struct {
Message Message `json:"message"`
}
type Message struct {
Action string `json:"action"`
Model string `json:"model"`
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论