0

How I can remove empty parameters from jq output without editing and removing a empty spaces from variable?

My output is, and I need remove this empty values like {"{#PARAMETER}":""}:

{"data":[{"{#PARAMETER}":""},{"{#PARAMETER}":"test1"},{"{#PARAMETER}":"test2"},{"{#PARAMETER}":"test3"},{"{#PARAMETER}":"test4"},{"{#PARAMETER}":""}]}

Reproduce script.

#!/bin/bash

TEST="
test1
test2
test3
test4
"

echo -n "${TEST}" | jq -R -s -c '{data:  split("\n") | map({"{#PARAMETER}": (.)}) }'
3
  • 1
    It'd be simpler to remove the extra newlines from $TEST, or filter the output from echo before it gets passed to jq. You don't want to do either of those? Commented Dec 8, 2020 at 22:29
  • 1
    Aside: Always use printf %s "$var" instead of echo -n "$var". Depending on which runtime configuration flags are active, echo -n can just echo -n instead of suppressing newlines -- and it's perfectly within POSIX specifications to do so! (See in particular the APPLICATION USAGE and RATIONALE sections of pubs.opengroup.org/onlinepubs/9699919799/utilities/echo.html, and note all the uses of "implementation-defined" within that spec). Commented Dec 8, 2020 at 23:00
  • 1
    Similarly, echo "\t" can legally replace that \t with a tab character even without a -e; indeed, doing anything other than printing -e as output when it's passed as an argument violates POSIX, which is part of why bash has runtime-configurable flags to change how echo behaves, so it's at least capable of being made strictly-compliant. Commented Dec 8, 2020 at 23:02

1 Answer 1

3
jq '.data[] |= select((."{#PARAMETER}" | length) > 0)' file.json
Sign up to request clarification or add additional context in comments.

3 Comments

When I do this like jq -R -s -c '{data: split("\n") | map({"{#PARAMETER}": (.)}) } | .data[] | select((."{#PARAMETER}" | length) > 0)', jq ignore -c parameter and do output line by line- do you have resolution?
It doesn't work with -R for me at all. Create a new question to ask a new question.
Ok, I found solution. Problem has been in version 1.5, after download 1.6 it's self resolved. Thanks for help anyway <3

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.