Velvet Star Monitor

Standout celebrity highlights with iconic style.

general

jq: error: number and string cannot be added

Writer Matthew Harrington

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
1

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.

1

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.

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy