简体   繁体   English

使用 jq 将 json 转换为 csv

[英]Using jq to convert json to csv

I'm trying to come up with the correct jq syntax to convert json to csv.我正在尝试提出正确的 jq 语法来将 json 转换为 csv。

Desired results:预期结果:

<email>,<id>,<name>
e.g. 
user1@whatever.nevermind.no,0,general
user2@whatever.nevermind.no,0,general
user1@whatever.nevermind.no,1,local
...
  • note that also need to ignore objects with empty "agent_priorities"请注意,还需要忽略具有空“agent_priorities”的对象

Input输入

[
  {
    "id": 0,
    "name": "General",
    "agent_priorities": {
      "user1@whatever.nevermind.no": "normal",
      "user2@whatever.nevermind.no": "normal"
    }
  },
  {
    "id": 1,
    "name": "local",
    "agent_priorities": {
      "user1@whatever.nevermind.no": "normal"
    }
  },
  {
    "id": 2,
    "name": "Engineering",
  }
]

Store the id and name in variables, then iterate over the keys of agent_priorities :将 id 和 name 存储在变量中,然后遍历agent_priorities的键:

jq -r '.[] 
       | .id as $id 
       | .name as $name 
       | .agent_priorities 
       | keys 
       | .[] 
       | [., $id, $name ] 
       | @csv
      ' file.json

The following variant of the accepted answer checks for the existence of the "agent_priorities" key as per the requirements, and uses keys_unsorted to preserve the order of the keys:接受的答案的以下变体根据要求检查“agent_priorities”键的存在,并使用keys_unsorted保留键的顺序:

jq -r '
       .[] 
       | select(has("agent_priorities"))
       | .id as $id 
       | .name as $name 
       | .agent_priorities 
       | keys_unsorted[]
       | [., $id, $name ] 
       | @csv
      ' file.json

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

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