Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use jq to convert number to string?

Tags:

json

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?

like image 821
AXE Labs Avatar asked Feb 02 '16 17:02

AXE Labs


People also ask

How do you convert a number variable value to a string?

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.

What is JQ query?

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.

How do you remove quotes from JQ output?

If you want to strip the quotes, just pipe the output from this command to tr -d '"' .


1 Answers

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 
like image 164
AXE Labs Avatar answered Dec 11 '22 20:12

AXE Labs