How do I use jq to convert number to string?

JsonJq

Json Problem Overview


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?

Json Solutions


Solution 1 - Json

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

Solution 2 - Json

An alternative and arguably more intuitive format is:

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

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

Solution 3 - Json

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

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

See it in action on jq‣play.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAXE LabsView Question on Stackoverflow
Solution 1 - JsonAXE LabsView Answer on Stackoverflow
Solution 2 - JsonAndrew NeilsonView Answer on Stackoverflow
Solution 3 - JsonmanatworkView Answer on Stackoverflow