【问题标题】:Split a JSON to multiple lines using UNIX command line tools使用 UNIX 命令行工具将 JSON 拆分为多行
【发布时间】:2021-03-01 07:54:02
【问题描述】:

我们有一个 JSON 文件需要多行而不是单行,如下所示,

{this is the first block},{this is the second block, really},{this is the third you're kidding:no}

我们希望它是这样的,以便可以将其馈送到外部程序以毫无问题地读取它,

{this is the first block}
{this is the second block, really}
{this is the third you're kidding:no}

我不是 awk、sed、cut 等简单文本处理工具方面的专家,但我确实尝试使用 sed 有一段时间没有成功。

cat test.json | sed 's/},/\n/g'
{this is the first block
{this is the second block, really
{this is the third you're kidding:no}

最好的方法是什么?

【问题讨论】:

  • 似乎您在 sed 尝试中需要 }\n 而不是 \n
  • 您的输入不是 JSON
  • 要成为 JSON,它需要在一个数组中,以 [ 开头并以 ] 结尾。你的真实数据是这样的吗?
  • (如果是这样,jq -c '.[]' <infile.json 将完成这项工作)。
  • 为了说明@CharlesDuffy的评论echo '[{"a":0},{"b":1},{"c":2}]' | jq -c '.[]'

标签: linux bash sed scripting cut


【解决方案1】:

Awk 替代方案:

awk 'BEGIN { RS="(,?{)|(},?)" } /[[:alnum:]]/ { print $0="{"$0"}" }' file

将记录分隔符设置为一个或多个逗号和 { 或 } 以及一个或多个逗号。然后,当遇到字母数字字符串时,为字符串添加前缀 {,附加 } 并打印

【讨论】:

    【解决方案2】:

    因为它不是 JSON,你只想拆分:

    input_file

    {this is the first block},{this is the second block, really},{this is the third you're kidding:no}
    
    sed 's/},/}\n/g' input_file
    

    output

    {this is the first block}
    {this is the second block, really}
    {this is the third you're kidding:no}
    

    【讨论】:

    • 我使用另一个 sed 命令删除了原始 JSON 文件的方括号,但你是对的,这个示例不再是 JSON。谢谢你的回答。
    猜你喜欢
    • 2017-03-16
    • 2014-05-14
    • 1970-01-01
    • 1970-01-01
    • 2016-05-20
    • 2020-05-14
    • 1970-01-01
    • 2013-11-14
    • 1970-01-01
    相关资源
    最近更新 更多