Home > Software engineering >  Converting a line of text into another format with jq avoiding 'if-then-else'
Converting a line of text into another format with jq avoiding 'if-then-else'

Time:11-13

Using jq, I want to convert the input A B=1 C= D=2 to "A", "B": "1", "C": "", "D": "2"

I came up with the solution

jq -Rr '. / " " | map(. / "=" | "\"\(.[0])\""   (if .[1] != null then ": \"\(.[1])\"" else "" end)) | join(", ")'

I am sure there is a more elegant way that avoids the if-then-else. Can you help me shorten the expression?

CodePudding user response:

Try this :

jq -Rr '
    . / " " |
    map(. / "=" |
          "\""   join("\": \"")   "\""
       ) |
    join(", ")
' input.json
  • Related