Search code examples
jsoncsvexport-to-csvjq

Using jq to convert json to csv


I'm trying to come up with the correct jq syntax to convert json to 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"

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",
  }
]

Solution

  • 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:

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