【问题标题】:Remove duplicates in JSON to CSV values using jq使用 jq 将 JSON 中的重复项删除为 CSV 值
【发布时间】:2021-12-21 15:35:09
【问题描述】:

在这里,我正在尝试将 json 转换为 csv。另外,我试图忽略同一命令中“颜色”属性的重复值。我尝试使用下面的 jq cmd 并得到 bash: syntax error near unexpected token `(' 错误。请帮我解决这个错误。

 jq -r '["color","category","type"], ([].colors | 'unique_by(.color)' | [.color, .category, .type]) | @csv' test.json > test.csv

我的 JSON 文件:

{
  "colors": [
    {
      "color": "black",
      "category": "hue",
      "type": "primary",
      "code": {
        "rgba": [255,255,255,1],
        "hex": "#000"
      }
    },
    {
      "color": "white",
      "category": "value",
      "code": {
        "rgba": [0,0,0,1],
        "hex": "#FFF"
      }
    },
    {
      "color": "red",
      "category": "hue",
      "type": "primary",
      "code": {
        "rgba": [255,0,0,1],
        "hex": "#FF0"
      }
    },
    {
      "color": "black",
      "category": "hue",
      "type": "primary",
      "code": {
        "rgba": [0,0,255,1],
        "hex": "#00F"
      }
    },
    {
      "color": "yellow",
      "category": "hue",
      "type": "primary",
      "code": {
        "rgba": [255,255,0,1],
        "hex": "#FF0"
      }
    },
    {
      "color": "white",
      "category": "hue",
      "type": "secondary",
      "code": {
        "rgba": [0,255,0,1],
        "hex": "#0F0"
      }
    }
  ]
}

【问题讨论】:

  • 单引号下为什么又出现了unique_by表达式?
  • 我删除了那些单引号并再次尝试。获取索引号问题..

标签: syntax duplicates jq export-to-csv


【解决方案1】:

你在找这个吗?

 jq -r '.colors | unique_by(.color)[] | [.color, .category, .type] | @csv'
"black","hue","primary"
"red","hue","primary"
"white","value",
"yellow","hue","primary"

Demo


要添加默认值(并使每一行具有相同数量的值),请在创建最终数组时添加// "<default_value>"。例如,"" 默认为:

 jq -r '.colors | unique_by(.color)[] | [.color//"", .category//"", .type//""] | @csv'
"black","hue","primary"
"red","hue","primary"
"white","value",""
"yellow","hue","primary"

Demo

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-07-06
  • 2019-12-13
  • 1970-01-01
  • 2015-06-22
  • 2020-09-23
相关资源
最近更新 更多