'Skip or Ignore non-existing key with to_entries in jq

I'm trying to create a massive CSV file converted from each *.json file. This snippet works until it faces the file that doesn't have the key (hobby).

Original

{
  "name": "bob",
  "hobby": [
    "baseball",
    "baseketball"
   ]
}

jq snippet

cat *.json | jq '.name as $n | .hobby | to_entries[] | [ $n, .value]'

It works

[][]... is a pre-format when creating CSV with jq

[
  "bob",
  "baseball"
]
[
  "bob",
  "baseketball"
]

https://jqplay.org/s/L-SmqiN-jw

However if the .hobby key doesn't exist it fails miserably.

jq: error (at <stdin>:6): null (null) has no keys
exit status 5

https://jqplay.org/s/gapUv1Tpmb

I tried to use if block but it seems not correct. How can we do such a thing either

  • return [] (empty array)
  • skip jq excution for the current working file with this problem and go to the next


Solution 1:[1]

One of many possibilities would be to use try:

.name as $n | .hobby | try to_entries[] | [ $n, .value]

try EXP is equivalent to try EXP catch empty.

Solution 2:[2]

Enter the following:

{
  "name": "bob",
  "hobby": [
    "baseball",
    "baseketball"
  ]
}

$ cat file | jq -c "{name,hobby:.hobby[]}|[.[]]"

["bob","baseball"]
["bob","baseketball"]

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 peak
Solution 2 focog77269