登录
首页 >  Golang >  Go问答

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

来源:stackoverflow

时间:2024-04-06 12:03:37 286浏览 收藏

在IT行业这个发展更新速度很快的行业,只有不停止的学习,才不会被行业所淘汰。如果你是Golang学习者,那么本文《如何解析正在处理的 JSON 文件》就很适合你!本篇内容主要包括##content_title##,希望对大家的知识积累有所帮助,助力实战开发!

问题内容

我有一个具有以下格式的 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 不正确。

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

如何访问文件并将它们解析为 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 文件》的详细内容,更多关于的资料请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>