我有一个格式为JSON的文件:
[{
"id": "1055972353245622272",
"lang": "und",
"date": "Sat Oct 27 00:00:02 +0000 2018",
"text": "#BTC 6474 346 0 08 #ETH 203 317 0 13 #XRP 0 459 0 04 #BCH 438 922 0 0 #EOS 5 388 0 12 #XLM 0 235 0 41 #LTC 52 106 0 03 #ADA 0 074 0 17 #USDT 0 99 0 07 #XMR 105 022 0 13 #TRX 0 024 0 21 "
},
{
"id": "1055972355506401280",
"lang": "en",
"date": "Sat Oct 27 00:00:03 +0000 2018",
"text": "Don t want to miss any of our public #crypto trading #signals Want instant updates of our premium channel #performance Searching for #crypto news Get instantly notified on our public telegram channel Join now at https t co akfmLiArya #DGB #SC #MFT #EOS #XVG #BTC #TRX https t co HT2RAOIjfh"
},
程序1 正在随机间隔(当找到匹配过滤器的推文时)正在处理此文件。我想在5分钟的时间内通过 program2 读取此文件。 但是我做不到。
解组(json.Unmarshal(file, &data)
)不允许我读取它-因为JSON不正确,它会引发错误。
我不想使用DB来重新设计体系结构,我希望能够按预期对文件进行操作。
如何访问文件并将其解析为JSON?
EDIT1:读取文件并关闭JSON的解决方法
file, _ := ioutil.ReadFile(fileName)
closingJson := "{}]"
file = append(file, closingJson...)
json.Unmarshal(file, &data)
答案 0 :(得分:1)
您只需要将其视为JSON stream:
https://play.golang.org/p/6drcizYKrrJ
type Message struct {
Id string `json:"id"`
Lang string `json:"lang"`
Date string `json:"date"`
Text string `json:"text"`
}
jsonStream, err := os.Open(`/tmp/json`)
if err != nil {
panic(err)
}
dec := json.NewDecoder(jsonStream)
// read open bracket
_, err := dec.Token()
if err != nil {
log.Fatal(err)
}
// while the array contains values
for dec.More() {
var m Message
// decode an array value (Message)
err := dec.Decode(&m)
if err == nil {
fmt.Printf("%v : %v : %v : %v\n", m.Id, m.Lang, m.Date, m.Text)
} else {
// wait for more contents - sleep? use a channel and wait to be notified?
}
}