Get or default function in jq?

后端 未结 2 702
天命终不由人
天命终不由人 2021-01-12 05:44

Assuming there is a json file:

{
  \"columns\": {
    \"id\": {
      \"required\": true,
      \"type\": \"integer\"
    },
    \"name\": {
      \"required         


        
相关标签:
2条回答
  • 2021-01-12 06:13

    Use alternative operator (//):

    $ jq '.columns.description | .required // false' file
    false
    
    0 讨论(0)
  • 2021-01-12 06:19

    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 ;.)

    0 讨论(0)
提交回复
热议问题