Skip to content

Extract multi segments of a json file and merge them into 1 line with jq

使用jq提取json中多个字段并输出到同一行

问题描述

例如,一下这段 example.json,想提取 usercmd 两个(或多个)字段,并输出在一行,用逗号和空格分割

{
  "user": "alex",
  "num": "486",
  "time": "Thu Jun  6 16:26:06 PDT 2019",
  "pwd": "/Users/alex/codes/ores/prompt-command",
  "pid": 11047,
  "exit_code": 0,
  "cmd": "echo '123'"
}
{
  "user": "john",
  "num": "487",
  "time": "Thu Jun  6 16:26:24 PDT 2019",
  "pwd": "/Users/alex/codes/ores/prompt-command",
  "pid": 11108,
  "exit_code": 5,
  "cmd": "echo '456'"
}
{
  "user": "alex",
  "num": "488",
  "time": "Thu Jun  6 16:26:59 PDT 2019",
  "pwd": "/Users/alex/codes/ores/prompt-command",
  "pid": 11141,
  "exit_code": 5,
  "cmd": "echo '789'"
}

jq命令组合

jq '. | "\(.user) , \(.cmd)"' example.json
  • 要想消除输出的引号,可以使用 -r 选项调用 jq

Disclaimer
  1. License under CC BY-NC 4.0
  2. Copyright issue feedback me#imzye.me, replace # with @
  3. Not all the commands and scripts are tested in production environment, use at your own risk
  4. No privacy information is collected here
Try iOS App