71

I use jq to transform a complex json object into a tinier one. My query is:

jq 'to_entries[]| {companyId: (.key), companyTitle: (.value.title), companyCode: (.value.booking_service_code)}' companies.json

Now, the (.key) is parsed as a string, yet I want companyId to be a number.

My result currently looks like this:

{
  "companyId": "1337",
  "companyTitle": "Some company title",
  "companyCode": "oxo"
}

yet it should be like:

{
  "companyId": 1337,
  "companyTitle": "Some company title",
  "companyCode": "oxo"
}

3 Answers 3

92

jq has inbuilt functions, you can pipe your key to tonumber:

jq 'to_entries[]| {companyId: (.key)|tonumber, companyTitle: (.value.title), companyCode: (.value.booking_service_code)}' companies.json

As per the docs:

tonumber The tonumber function parses its input as a number. It will convert correctly-formatted strings to their numeric equivalent, leave numbers alone, and give an error on all other input.

Example jq '.[] | tonumber' Input [1, "1"] Output 1 1

Sign up to request clarification or add additional context in comments.

2 Comments

Anyway to do this while somehow handling null values?
@Canovice Please open a new question with that requirement. You can link this answer there.
10

I was trying to turn my string (that converts to a float) to an integer. I was looking for a 'toint' function, one doesn't exist.

jq --arg str "1.435" -n '$str|tonumber'
1.435

I threw a floor in there to make sure the number that was created was an integer:

jq --arg str "1.435" -n '$str|tonumber|floor'
1

This also properly converts the OP original data as well. If you want to guarantee your result is an integer you will need to floor it.

2 Comments

Or perhaps round.
For anyone wondering why there is no toint function, this is because there’s no such thing as integers or floats in JSON, there are only "numbers", like in JS.
2

Warning: using tonumber WILL remove any prefixed zeros like: "data":{"order_number":"024058275" => 24058275

use sed ( or awk ) to remove the ' " '

echo $result | jq '.data.order_number' | sed 's|["]||g'

This will return 024058275

1 Comment

["] can be shortenen as "

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.