简体   繁体   English

如何优化jq输出

[英]how to refine jq output

I have a json file. 我有一个json文件。 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. 我想提取“主机”和“ ip”值,并将它们添加到以逗号分隔的值文件中。 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. 我安装了jq库来解析json文件。 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. jq生成的此输出需要其他脚本来解析它,并将所需的值保存为csv格式(一行中的一项)。

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 . 如果使用OS X,请使用Homebrew安装GNU sed

Use the @csv format to produce CSV output from an array of the values. 使用@csv格式从值数组生成CSV输出。

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. 需要-r选项来获取原始输出,而不是JSON,这将在结果周围包裹额外的引号并转义包围每个字段的引号。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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