简体   繁体   中英

how to refine jq output

I have a json file. A simple example looks like:

[
{
  "host": "a.com",
  "ip": "1.2.2.3",
  "port": 8,
  "name":"xyz"
},
{
  "host": "b.com",
  "ip": "2.5.0.4",
  "port": 3,
  "name":"xyz"

},
{
  "host": "c.com",
  "ip": "9.17.6.7",
  "port": 4,
  "name":"xyz"
}
]

I want to extract the "host" and "ip" value and add them in a comma separated values file. Each record in a line as follows:

a.com,1.2.2.3
b.com,2.5.0.4
c.com,9.17.6.7

I installed jq library to parse the json file. I executed this command:

cat test.json | jq '.[] | {host: .host, ip: .ip}'

The output I get is as the following:

{
  "host": "a.com",
  "ip": "1.2.2.3"
}
{
  "host": "b.com",
  "ip": "2.5.0.4"
}
{
  "host": "c.com",
  "ip": "9.17.6.7"
}

Is there any way I can extract the output as I want? This output that jq produced require additional script to parse it and save the values as I want in csv format, one item in a line.

To remove quotes:

$ cat test.json | jq -r '.[] | [ .host, .ip ] | @csv' | sed 's/"//g'
a.com,1.2.2.3
b.com,2.5.0.4
c.com,9.17.6.7

If using OS X, use Homebrew to install GNU sed .

Use the @csv format to produce CSV output from an array of the values.

cat test.json | jq -r '.[] | [.host, .ip] | @csv'

The -r option is needed to get raw output rather than JSON, which would wrap an extra set of quotes around the result and escape the quotes that surround each field.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM