How to perform mathematical operations in JQ
JQ provides several built-in functions for performing mathematical operations on numbers. Here's how to perform basic calculations, aggregations, and work with numbers in JQ.
Basic Calculations
Given this JSON input:
{
"numbers": [1, 2, 3, 4, 5],
"price": 19.99,
"quantity": 3,
"measurements": {
"length": 10,
"width": 5
}
}
Example Expressions and Output
Here are various mathematical operations you can perform:
# Basic arithmetic with single values
.price * .quantity
# Output: 59.97
# Calculate area using object values
.measurements.length * .measurements.width
# Output: 50
# Array operations
.numbers | add # Sum of array
# Output: 15
.numbers | add / length # Average of array
# Output: 3
.numbers | max # Maximum value
# Output: 5
.numbers | min # Minimum value
# Output: 1
# Round numbers
.price | floor # Round down
# Output: 19
.price | ceil # Round up
# Output: 20
.price | round # Round to nearest integer
# Output: 20
# Absolute value
-15.7 | abs # Absolute value
# Output: 15.7
Advanced Examples
You can also chain operations together:
# Calculate percentage
.numbers | (add / length) * 100
# Output: 300
# Round to specific decimal places
.price * .quantity | round * 0.01
# Output: 59.97
Complex example: Calculate statistics for a shopping cart
{
"total": (.price * .quantity),
"roundedTotal": (.price * .quantity | round * 0.01),
"numbers_stats": {
"sum": (.numbers | add),
"average": (.numbers | add / length),
"range": (.numbers | max - min)
},
"area": {
"value": (.measurements.length * .measurements.width),
"perimeter": ((.measurements.length + .measurements.width) * 2)
}
}
# Output:
# {
# "total": 59.97,
# "roundedTotal": 60,
# "numbers_stats": {
# "sum": 15,
# "average": 3,
# "range": 4
# },
# "area": {
# "value": 50,
# "perimeter": 30
# }
# }
You can play with this example in the JQ Playground: JQ Playground.