简体   繁体   English

从 jq json 输出中排除列

[英]Exclude column from jq json output

I would like to get rid of the timestamp<\/code> field here using jq<\/a> JSON processor.我想在这里使用jq<\/a> JSON 处理器摆脱timestamp<\/code>字段。

[
  {
    "timestamp": 1448369447295,
    "group": "employees",
    "uid": "elgalu"
  },
  {
    "timestamp": 1448369447296,
    "group": "employees",
    "uid": "mike"
  },
  {
    "timestamp": 1448369786667,
    "group": "services",
    "uid": "pacts"
  }
]

If you just want to delete the timestamps you can use the del() function: 如果您只想删除时间戳,可以使用del()函数:

jq 'del(.[].timestamp)' input.json

However to achieve the desired output, I would not use the del() function. 但是为了实现所需的输出,我不会使用del()函数。 Since you know which fields should appear in output, you can simply populate an array with group and id and then use the join() function: 既然您知道哪些字段应该出现在输出中,您只需使用groupid填充数组,然后使用join()函数:

jq -r '.[]|[.group,.uid]|join(",")' input.json

-r stands for raw ouput . -r代表原始输出 jq will not print quotes around the values. jq不会在值周围打印引号。

Output: 输出:

employees,elgalu
employees,mike
services,pacts

For the record, an alternative would be: 为了记录,另一种选择是:

$ jq -r '.[] | "\(.uid),\(.group)"' input.json

(The white-listing approach makes it easy to rearrange the order, and this variant makes it easy to modify the spacing, etc.) (白名单方法可以轻松重新排列顺序,这种变体可以很容易地修改间距等)

The following example may be of interest to anyone who wants safe CSV (ie even if the values have embedded commas or newline characters): 以下示例可能是任何想要安全CSV的人感兴趣的(即使值已嵌入逗号或换行符):

$ jq -r '.[] | [.uid, .group] | @csv' input.json
"elgalu","employees"
"mike","employees"
"pacts","services"

Sed 是你最好的朋友——我想不出更简单的方法,我在这里遇到了与问题作者相同的问题——但也许这是对同一问题的更简单的答案:

< file sed -e '/timestamp/d'

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

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