127

Given the following jq command and Json:

jq '.[]|[.string,.number]|join(": ")' <<< '
[
  {
    "number": 3,
    "string": "three"
  },
  {
    "number": 7,
    "string": "seven"
  }
]
'

I'm trying to format the output as:

three: 3
seven: 7

Unfortunately, my attempt is resulting in the following error:

jq: error: string and number cannot be added

How do I convert the number to string so both can be joined?

3 Answers 3

127

The jq command has the tostring function. It took me a while to learn to use it by trial and error. Here is how to use it:

jq -r '.[] | [ .string, .number|tostring ] | join(": ")' <<< '
[{ "number": 9, "string": "nine"},
 { "number": 4, "string": "four"}]
'
nine: 9
four: 4
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you very helpful, I find jq hard to use and poorly documented so these examples really help.
.number|tostring worked perfectly
Note that if the .number|tostring is the first element of the array, it will fail. See below for note about surrounding with parens to avoid the error.
83

An alternative and arguably more intuitive format is:

jq '.[] | .string + ": " + (.number|tostring)' <<< ...

Worth noting the need for parens around .number|tostring.

3 Comments

For my use case I had to keep the parentheses to prioritize things. It's better to keep them for general use cases.
Thank you! I found this working for me too for concat purposes, after spending hours trying in vain to make sense of jq's horribly poor documentation! (and agreed, this is more intuitive than the answer above it.)
I agree it's more intuitive and naturally follows when incrementally building a statement.
19

For such simple case string interpolation's implicit casting to string will do it:

.[] | "\( .string ): \( .number )"

See it in action on jq‣play.

2 Comments

@Ярослав Рахматуллин, that's not useless escapes. That's jq's string interpolation syntax. Ruby has "#{ 1 + 2 }", Groovy has "${ 1 + 2 }", jq has "\( 1 + 2 )".
btw, Swift has the same string interpolation syntax

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.