105

Given the following jq command and Json:

jq '.[]|[.string,.number]|join(": ")' <<< '
[
  {
    "number": 3,
    "string": "threee"
  },
  {
    "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?

spcsLrg
  • 340
  • 2
  • 11
AXE Labs
  • 4,051
  • 4
  • 29
  • 29

3 Answers3

104

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
AXE Labs
  • 4,051
  • 4
  • 29
  • 29
68

An alternative and arguably more intuitive format is:

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

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

Andrew Neilson
  • 813
  • 6
  • 6
  • 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 '20 at 13:22
  • 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 '22 at 13:22
16

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

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

See it in action on jq‣play.

manatwork
  • 1,689
  • 1
  • 28
  • 31
  • 1
    @Ярослав Рахматуллин, that's not useless escapes. That's jq's string interpolation syntax. Ruby has [`"#{ 1 + 2 }"`](https://tio.run/##KypNqvz/v6C0pFhBKSk1Lb8oVUG5WsFQQVvBSKFWITGtJLVI6f9/AA), Groovy has [`"${ 1 + 2 }"`](https://tio.run/##Sy/Kzy@r/P@/oCgzr0RDKSk1Lb8oVUGlWsFQQVvBSKFWITGtJLVISfP/fwA), jq has [`"\( 1 + 2 )"`](https://tio.run/##yyr8/18pKTUtvyhVIUZDwVBBW8FIQVMhMa0ktUjp//9/@QUlmfl5xf918wA). – manatwork Dec 18 '20 at 00:41
  • btw, Swift has the same string interpolation syntax – Walter Tross Oct 07 '21 at 13:38