文本文件转 JSON

文本文件转 JSON

我有一个文本文件IP:PORT,例如

1.1.1.1:1919
2.2.2.2:111
1.1.1.1:987

我需要在 JSON 格式的脚本中使用它们:

async def main(loop):
    servers = [{
        "address": "ip",
        "port": port
    }, {
        "address": "ip",
        "port": port
    }]

我需要输出为

async def main(loop):
    servers = [{
        "address": "1.1.1.1",
        "port": 1919
    }, {
        "address": "2.2.2.2,
        "port": 111
    }, {
        "address": "1.1.1.1,
        "port": 987
    }]

我正在使用Linux。

答案1

jq -nRr '
    [ inputs | split(":") | {address: first, port: last} ]
    | "async def main(loop):\n    servers = \(.)"
' addresses

输出

async def main(loop):
    servers = [{"address":"1.1.1.1","port":"1919"},{"address":"2.2.2.2","port":"111"},{"address":"1.1.1.1","port":"987"}]

答案2

使用(以前称为 Perl_6)

raku -MJSON::Fast -e 'my @a.=push(.split: ":") for lines; say to-json( ( %("address", .[0], "port", .[1].Int) for @a), :sorted-keys );'  

输入示例:

1.1.1.1:1919
2.2.2.2:111
1.1.1.1:987

示例输出:

    [
      {
        "address" : "1.1.1.1",
        "port" : 1919
      },
      {
        "address" : "1.1.1.1",
        "port" : 987
      },
      {
        "address" : "2.2.2.2",
        "port" : 111
      }
    ]

注意:可以通过设置获得非漂亮打印的输出pretty => False

~$ raku -MJSON::Fast -e 'my @a.=push(.split: ":") for lines; say to-json( ( %("address", .[0], "port", .[1].Int) for @a), pretty => False );'  file
[{"address":"1.1.1.1","port":1919},{"port":111,"address":"2.2.2.2"},{"port":987,"address":"1.1.1.1"}]

Raku 生态系统中的其他相关模块包括JSON::TinyJSON::Pretty、 和JSON::Pretty::Sorted

https://raku.land/cpan:TIMOTIMO/JSON::Fast
https://raku.org

相关内容