Home > Software engineering >  Convert key=value pair from jq output to comma seperated string
Convert key=value pair from jq output to comma seperated string

Time:09-20

I have this json stored in a variable foo

{
"app":   "myApp",
"env":   "test",
"tier":  "frontend"
}

I have converted it into key=value pair using the following jq command:

jq -r 'to_entries[] | (.key)   "="   .value' <(echo "$foo")

Output:

app =  myApp
env =  test
tier= frontend

I need to transform this to a comma seperated string of following string format and store in a variable:

Expected Output:

app=myApp,env=test,tier=frontend

What I tried:

jq -r 'to_entries[] | (.key)   "="   .value| join(",")' <(echo "$foo")

But got error jq: error (at <stdin>:4): Cannot iterate over string ("app=myApp")

CodePudding user response:

join() works on an array, but you're returning single items.

Replace [] with map() so we keep the array, then join will work just fine:

to_entries | map(.key   "="   .value) | join(",")

JqPlay Demo
  • Related