json - 如何解析正在处理的 JSON 文件

标签 json file go unmarshalling

我有一个格式为 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"
},

此文件由 program1 以随机间隔处理(当找到匹配过滤器的推文时)。我想通过 program2 阅读这个文件 - 在 5 分钟的时间步长内。 但是我做不到。

解码 (json.Unmarshal(file, &data)) 不允许我读取它 - 因为它会抛出错误,因为 JSON 不正确。

我不想使用 DB 重新设计架构,我希望能够按预期操作文件。

如何访问文件并将它们解析为 JSON?

读取文件并关闭 JSON 的解决方法

file, _ := ioutil.ReadFile(fileName)
closingJson := "{}]"
file = append(file, closingJson...)
json.Unmarshal(file, &data)

最佳答案

你只需要把它当作一个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?
      }

    }

关于json - 如何解析正在处理的 JSON 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53575401/

相关文章:

python - 将字典列表转换为数据框

python - 如何在 python 中有效地加载大文本文件

json - 从 Go 中的 json 文件中读取多个 json 对象

go - embedded 和 field 的区别

jquery - 将 jQuery 中的 JSON 解析为 div 标签

javascript - 邮政编码验证格式 nnnnn-nnnn

java - 输出解析后的Json数据

Java如何将字符串以字节形式写入文件并获取字符串

file - 检查文件是否从另一个进程打开

go - 为什么fasthttp像单进程?