Reputation: 2398
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.
Upvotes: 0
Views: 2261
Reputation: 96947
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
.
Upvotes: 1
Reputation: 781096
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.
Upvotes: 0