【问题标题】:jq array of hashes to csvjq 散列数组到 csv
【发布时间】:2018-07-01 22:50:35
【问题描述】:

所以我有一个这样的数据源:

{
  "things": [
    {
      "thing_name": "Bestco",
      "thing_id": 1
    },
    {
      "thing_name": "GreatCo",
      "thing_id": 2
    },
    {
      "thing_name": "DressCo",
      "thing_id": 3
    }
  ]
}

我想得到这样的输出:

$ echo '{"things":[{"thing_name":"Bestco","thing_id":1},{"thing_name":"GreatCo","thing_id":2},{"thing_name":"DressCo","thing_id":3}]}' |
  jq -r '.things | map(.thing_name, .thing_id, "\n") | @csv' |
  sed -e 's/,"$//g' -e 's/^",//g' -e 's/^"$//g'
"Bestco",1
"GreatCo",2
"DressCo",3

$ 

使用假参数似乎是一种 hack,然后需要通过 sed 清理才能工作。我如何只用 jq 做到这一点。

【问题讨论】:

    标签: json linux csv jq


    【解决方案1】:

    不要尝试在数据中添加文字换行符,而是将数据拆分为单独的数组(每行所需输出一个),并将每个数组传递给 @csv

    s='{"things":[{"thing_name":"Bestco","thing_id":1},{"thing_name":"GreatCo","thing_id":2},{"thing_name":"DressCo","thing_id":3}]}'
    
    jq -r '.things[] | [.thing_name, .thing_id] | @csv' <<<"$s"
    

    ...正确发出:

    "Bestco",1
    "GreatCo",2
    "DressCo",3
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-06
      • 2022-01-16
      • 1970-01-01
      • 1970-01-01
      • 2023-03-31
      • 2020-06-28
      相关资源
      最近更新 更多