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?
Using the str() Function The str() function can be used to change any numeric type to a string. The nice thing about str() is that it can handle converting any type of number to a string, so you don't need to worry about choosing the correct method based on what type of number you're converting.
A jq program is a "filter": it takes an input, and produces an output. There are a lot of builtin filters for extracting a particular field of an object, or converting a number to a string, or various other standard tasks.
If you want to strip the quotes, just pipe the output from this command to tr -d '"' .
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With