Skip to content

How to extract multi segments of a json file and merge them into 1 line with jq

homepage-banner

Extracting multiple fields from a JSON file using jq and outputting them on the same line.

Problem Description

For example, given the example.json file below, we want to extract the user and cmd fields (or multiple fields) and output them on the same line separated by a comma and a space.

{
  "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'"
}

Combining jq Commands

jq '. | "\(.user) , \(.cmd)"' example.json
  • To remove the quotes around the output, use the r option when calling jq.
Leave a message