nntrn / save

https://nntrn.github.io/save/
2 stars 0 forks source link

jq #24

Open nntrn opened 1 year ago

nntrn commented 1 year ago
nntrn commented 1 year ago

Examples

nntrn commented 1 year ago

Debug

(cat 1.json 2.json 1.json1) | jq -n '

# If cond is falsey, then (msg|debug); in all cases, emit .
def verify(cond; msg): 
  . as $in
  | if cond then . else (msg | debug) | $in end;

def valid_key: test("^[A-Za-z_][0-9A-Za-z_]*$");

def valid_value:
  type != "array" and 
  type != "object" and
  (type != "string" or (test("\u0000") | not) );

# $count is for the messages and for the return value
def validate($count):
   if type == "object"
   then to_entries[]
   | verify(.key | valid_key; "invalid key in entity #\($count): \(.key)")
   | verify(.value | valid_value; "invalid value in entity #\($count): \(.value)")
   else "entity #\($count) is not a JSON object" | debug
   end
   | $count;

reduce inputs as $in (0;
  .+1
  | . as $count
  | $in | validate($count) )
| verify(.==1; "only one entity is allowed")
| empty
'

Source

nntrn commented 12 months ago

Template

def template:
{
  key1: "value1",
  key2: "value2",
  name: "XXX",
  familyName: "YYY"
}
;

def fillin($template):
  . as $in
  | reduce ($template|keys_unsorted[]) as $k ($template; if $in|has($k) then .[$k] = $in[$k] else . end);
jq 'map(fillin(template))'

Source

nntrn commented 3 months ago

while

$ echo 5 | jq '[., ., 1] | [while(.[1] > 0; [.[0], .[1] - 1, .[2] * .[1]])] | .[length -1][2]'
120

until

$ echo 5 | jq '[., 1] | until(.[0] < 1; [.[0] - 1, .[1] * .[0]]) | .[1]'
120

Source

nntrn commented 3 months ago

indexof

https://stackoverflow.com/a/50134933

# Returns the integer index, $i, corresponding to the first element
# at which f is truthy, else null
def indexof(f):
  label $out
  | foreach .[] as $x (null; .+1; 
      if ($x|f) then (.-1, break $out) else empty end) // null;

# Change the string $base to BASE using gsub
def munge($base):
  if type == "string" and (test("^BASE=")|not) then gsub($base; "BASE")
  elif type=="array" then map(munge($base))
  elif type=="object" then map_values(munge($base))
  else .
  end;
nntrn commented 2 months ago

json2csv

jq -r '(.[0] | keys_unsorted) as $keys | $keys, map([.[ $keys[] ]])[] | @csv'

Source