I have the following simple JSON
json='[{"k1":" http://url", "k2":null, "k3":" v3", "k4":" v4"}]'
what I need is:
"http://url",null
(without a space before v1
and v2
)
What I have is:
echo $json | jq -c '.[] | .k1, .k2 ' | paste -d "," - -
How to get rid of the space in k1 and k2 values?
If the input is an array of JSON objects and if you're looking for a one-liner, then the following seems to meet your requirements:
jq '.[]|(.k1,.k2)|if type=="string" then gsub("^\\s+|\\s+$";"") else . end' | paste -d "," - -
With your input, this produces
"http://url",null
If you are flexible about how null
is presented in the output, you might also consider an all-jq solution (i.e. without paste
). For example:
jq -r '.[]|[.k1,.k2]|map(if type=="string" then gsub("^\\s+|\\s+$";"") else . end)|@csv'
With your input, this produces:
"http://url",
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With