Jq: Error: Number and String Cannot Be Added
I'd Like to Print the Value of Members and Id from Below Jq Output: $ Cat Test_|Jq -R '. [] | Select(. Name=="Aaa") |.' { "Name": "Aaa", "Members": 10...
I'd like to print the value of members and id from below jq output:
$ cat test_|jq -r '.[] | select(.name=="AAA") | .'
{
"name": "AAA",
"members": 10,
"profiles": 0,
"templates": 0,
"ldapGroups": 0,
"ldapMembers": 0,
"id": "20"
}
Unfortunately it works for one of each only:
$ cat test_|jq -r '.[] | select(.name=="AAA") | .members'
10
with +" "+ I get error:
$ cat test_|jq -r '.[] | select(.name=="AAA") | .members+" "+.id'
jq: error: number and string cannot be added
4 Answers
I recommend to use string interpolation. It will automatically cast input to a string if necessary:
jq -r '.[]|select(.name=="AAA")|"\(.members) \(.id)"' file.json
Convert number to string with tostring function:
jq -r '.[] | select(.name=="AAA") | (.members|tostring) +" "+ .id test'
You have not specified precisely how you want the two values to appear, so it is worth pointing out that you could write:
.... | (.members, .id)
or
.... | [.members, .id]
or
.... | [.members, .id] | E
where E could be @csv or @tsv or etc. In jq 1.5, join/1 will also do the type conversion.
You could start by just projecting the members of interest. e.g
$ jq -Mc '.[] | select(.name=="AAA") | {members,id}' data.json
{"members":10,"id":"20"}
Now you can see .members is a number and .id is a string. You can't add them directly with + but you can choose any of the options explained in the other answers.