简体   繁体   English

jq散列到csv的数组

[英]jq array of hashes to csv

So I have a data source like this: 所以我有一个像这样的数据源:

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

I want to get output like this: 我想要这样的输出:

$ 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

$ 

Using a fake parameter seems like a hack and then needs to be clean up by sed to work. 使用伪造的参数似乎很容易,然后需要通过sed进行清理才能工作。 How do I do this with just jq. 我如何只用jq做到这一点。

Instead of trying to put literal newlines in your data, split the data into separate arrays (one per line of desired output), and pass each one to @csv . 与其尝试在数据中添加文字换行符, @csv将数据分成单独的数组(每行所需的输出一个),然后将每个数组传递给@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"

...properly emits: ...正确发出:

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

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

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