如何从stdin中解析无限的json数组? [英] How to parse an infinite json array from stdin in go?

查看:164
本文介绍了如何从stdin中解析无限的json数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为i3status写一个小的替代品,这是一个与i3bar一致的小程序,符合这个协议。他们通过stdin和stdout交换消息。



两个方向的流都是无限数量的json对象。从i3bar到i3status(我想要替换)的流开始如下所示:

  [
{ name:some_name_1,instance:some_inst_1,button:1,x:213,y:35}
,{name:some_name_1,instance :some_inst_2,button:2,x:687,y:354}
,{name:some_name_2,instance:some_inst,button: 1,x:786,y:637}
,{name:some_name_3,instance:some_inst,button:3,x:768,y :67}
...

这是表示对象的数组点击。数组将永远不会关闭。



现在我的问题是:什么是正确的解析方式



显然,我不能使用 json 库,因为它不是vaild json对象。

解决方案

编写自定义阅读器函数(或解码器),它可以这样做流数组解析:
$ b


  1. 如果下一个字符不是 [,那么返回一个错误(不能是数组)。
  2. 尽管如此:


    1. 致电 json.Decoder.Decode 放入下一个项。

    2. 收益或处理下一个项目。

    3. 读取并放弃空白。

    4. 如果下一个字符是:


      1. 逗号然后继续#3中的for循环

      2. ] 然后退出for-lo在$ 3中运算。
      3. 否则返回一个错误(无效的数组语法)。



      I'm trying to write a small replacement for i3status, a small programm that comunicates with i3bar conforming this protocol. They exchange messeages via stdin and stdout.

      The stream in both directions is an infinite array of json objects. The start of the stream from i3bar to i3status (which i want to replace) looks like this:

      [
      {"name": "some_name_1","instance": "some_inst_1","button": 1,"x": 213,"y": 35}
      ,{"name": "some_name_1","instance": "some_inst_2","button": 2,"x": 687,"y": 354}
      ,{"name": "some_name_2","instance": "some_inst","button": 1,"x": 786,"y": 637}
      ,{"name": "some_name_3","instance": "some_inst","button": 3,"x": 768,"y": 67}
      ...
      

      This is an "array" of objects which represent clicks. The array will never close.

      My question is now: What is the right way of parsing this?

      Obviously I cannot use the json library because this is not a vaild json object.

      解决方案

      Write a custom reader function (or Decoder) which does a "streaming array parse" like so:

      1. Read and discard leading whitespace.
      2. If the next character is not a [ then return an error (can't be an array).
      3. While true do:

        1. Call json.Decoder.Decode into the "next" item.
        2. Yield or process the "next" item.
        3. Read and discard whitespace.
        4. If the next character is:

          1. A comma , then continue the for-loop in #3.
          2. A close bracket ] then exit the for-loop in #3.
          3. Otherwise return an error (invalid array syntax).

      这篇关于如何从stdin中解析无限的json数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆