114

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

113

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
1
  • 8
    Thank you very helpful, I find jq hard to use and poorly documented so these examples really help. Oct 2, 2019 at 19:01
72

An alternative and arguably more intuitive format is:

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

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

3
  • For my use case I had to keep the parentheses to prioritize things. It's better to keep them for general use cases.
    – SebMa
    Apr 30, 2020 at 13:22
  • 1
    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.)
    – spcsLrg
    Jan 12, 2022 at 13:22
  • I agree it's more intuitive and naturally follows when incrementally building a statement. Apr 4 at 4:12
17

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

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

See it in action on jq‣play.

2
  • 2
    @Ярослав Рахматуллин, that's not useless escapes. That's jq's string interpolation syntax. Ruby has "#{ 1 + 2 }", Groovy has "${ 1 + 2 }", jq has "\( 1 + 2 )".
    – manatwork
    Dec 18, 2020 at 0:41
  • 1
    btw, Swift has the same string interpolation syntax Oct 7, 2021 at 13:38

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.