Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to trim white space for every element in JQ?

Tags:

unix

trim

jq

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?

like image 734
Adam Siemion Avatar asked Dec 06 '22 14:12

Adam Siemion


1 Answers

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",
like image 94
peak Avatar answered Dec 22 '22 01:12

peak