Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get or default function in JQ?

Tags:

json

jq

Assuming there is a json file:

{
  "columns": {
    "id": {
      "required": true,
      "type": "integer"
    },
    "name": {
      "required": false,
      "type": "string"
    },
    "description": {
      "type": "string"
    }
  }
}

I want to use jq to get the value "required" field for each column. If the field "required" does not exist, it should return the default value false.

Specifically:

jq '.columns.id | getOrDefault("required", false)'  # true
jq '.columns.name | getOrDefault("required", false)'  # false
jq '.columns.description | getOrDefault("required", false)'  # false

How to implement this magic getOrDefault() function in jq?

like image 285
Yun Huang Avatar asked Jun 12 '19 05:06

Yun Huang


2 Answers

If the field "required" does not exist, it should return the default value false.

To implement that functionality literally, you would use has/1 rather than //, e.g.:

   .columns.id
   | if has("required") then .required else false end

If the .required field is known never to be specified as null, then the two techniques (using has as above and using // false) are equivalent.

getOrDefault/2

You'd almost surely never define such a function, but since you ask:

def getOrDefault($key; $default):
  if has($key) then .[$key] else $default end;

(NB: The argument separator in jq is ;.)

like image 38
peak Avatar answered Nov 13 '22 10:11

peak


You can use the alternative operator (//) in this particular case.

$ jq '.columns.description | .required // false' file
false

For a fail-safe, generally applicable approach, see peak's answer.

like image 66
oguz ismail Avatar answered Nov 13 '22 10:11

oguz ismail