How to get a new line at each iteration in jq

I have the following file

[
  {
    "id": 1,
    "name": "Arthur",
    "age": "21"
  },
  {
    "id": 2,
    "name": "Richard",
    "age": "32"
  }
]

To display login and id together, I use the following command

$ jq '.[] | .name' test
"Arthur"
"Richard"

But when I put it in a shell script and try to assign it to a variable, then all the output is displayed in one line, as shown below

#!/bin/bash

names=$(jq '.[] | .name' test)
echo $names

$ ./script.sh
"Arthur" "Richard"

I want to break up each iteration, similar to how it works on the command line.

Please, help

+4
source share
2 answers

A few questions in the information you provide. The filter jq .[] | .login, .idwill not display the result, as you stated on jq-1.5. For your originalJSON

{  
   "login":"dmaxfield",
   "id":7449977
}
{  
   "login":"stackfield",
   "id":2342323
}

It produces four lines of output, like

jq -r '.login, .id' < json
dmaxfield
7449977
stackfield
2342323

,

jq -r '"\(.login), \(.id)"' < json
dmaxfield, 7449977
stackfield, 2342323

, , , . , - , .

jqOutput=$(jq -r '"\(.login), \(.id)"' < json)
printf "%s\n" "$jqOutput"
dmaxfield, 7449977
stackfield, 2342323

, .


JSON ( ) , ,

jqOutput=$(jq -r '.[] | .name' < json)
printf "%s\n" "$jqOutput"
Arthur
Richard
+4

, .login .id , , , JSON . , :

jq -c .login,.id input.json | while read login ; do read id; echo login="$login" and id="$id" ; done
login="dmaxfield" and id=7449977
login="stackfield" and id=2342323
0

Source: https://habr.com/ru/post/1677511/


All Articles