每行以JSON格式输出对象

7
cat 2.txt | ./jq '{(.id): .custom}'

以上命令输出:
{
  "1": {
    "results": "Success"
  }
}
{
  "2": {

    "input method": "touch",
    "from": "Prescription Center",

  }
}
{
  "3": {

    "entry point": "|All"
  }

}

预期输出:
我想将每个对象打印/保存到一行中。
cat 2.txt | ./jq '{(.id): .custom}'

{ "1": {  "results": "Success" }  }
{ "2": {  "input method": "touch",  "from": "Prescription Center"  }  }
{ "3": {  "entry point": "|All" } }

能否在shell脚本中实现?

1
你尝试过使用 cat 2.txt | ./jq -c '{(.id): .custom}' 吗?(参考链接:http://stedolan.github.io/jq/manual/) - Prix
1
-c选项有效,谢谢。你可以将其发布在答案中,我会接受。jq是用于解析JSON的C程序。 - user2711819
我的Ubuntu不认识任何jq,你为什么在本地目录中有它?我对那个工具很感兴趣。 - Alfe
1
@Alfe,sudo apt-get install jq - glenn jackman
有趣。apt-file 没有显示出来,但是 apt-get 可以安装它。我猜我得学习更多关于这两个包管理工具的知识。谢谢! - Alfe
啊,一个 apt-file update 就解决了问题;现在 apt-file list 也显示了 jq 包。看起来是在最近几个月/年出现的(在我上次进行 apt-file update 之前)。 - Alfe
1个回答

17

根据jq手册

  • --compact-output / -c:

    默认情况下,jq会对JSON输出进行漂亮的打印。使用此选项将导致更紧凑的输出,而是将每个JSON对象放在一行上。

因此,以下内容应该可行:

cat 2.txt | ./jq -c '{(.id): .custom}'

4
jq非常可爱。 - avocado

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接