cli-tools
__HTML_TAG_159_ Todos los comandos jq_HTML_TAG_160__
Generar jq PDF Guide
jq Cheatsheet - Command-line JSON Procesador
Instalación
Platform
Command
Ubuntu/Debian
INLINE_CODE_8
RHEL/CentOS/Fedora
INLINE_CODE_9 or INLINE_CODE_10
Arch Linux
INLINE_CODE_11
macOS (Homebrew)
INLINE_CODE_12
macOS (MacPorts)
INLINE_CODE_13
Windows (Chocolatey)
INLINE_CODE_14
Windows (Scoop)
INLINE_CODE_15
Docker
INLINE_CODE_16
Verify Installation
INLINE_CODE_17
Comandos básicos
Command
Description
INLINE_CODE_18
Pretty-print JSON (identity filter)
INLINE_CODE_19
Extract specific field value
INLINE_CODE_20
Extract multiple fields
INLINE_CODE_21
Extract nested field value
INLINE_CODE_22
Get first element of array
INLINE_CODE_23
Array slice (elements 1-2)
INLINE_CODE_24
Iterate through all array elements
INLINE_CODE_25
Extract field from each array element
INLINE_CODE_26
Get length of array or object
INLINE_CODE_27
Get all keys from object (sorted)
INLINE_CODE_28
Get all keys in original order
INLINE_CODE_29
Get all values from object
INLINE_CODE_30
Check if object has specific key
INLINE_CODE_31
Get type of value (string, number, array, etc.)
INLINE_CODE_32
Raw output (no quotes for strings)
INLINE_CODE_33
Compact output (no pretty-printing)
INLINE_CODE_34
Sort object keys in output
INLINE_CODE_35
Read and process JSON from file
INLINE_CODE_36
Create JSON without input
INLINE_CODE_37
Produce no output
Advanced Usage
Command
Description
INLINE_CODE_38
Filter array elements by condition
INLINE_CODE_39
Apply operation to each array element
INLINE_CODE_40
Construct new object with renamed fields
INLINE_CODE_41
Conditional logic
INLINE_CODE_42
Group array elements by field value
INLINE_CODE_43
Sort array in ascending order
INLINE_CODE_44
Sort array of objects by field
INLINE_CODE_45
Reverse array order
INLINE_CODE_46
Get unique values from array
INLINE_CODE_47
Get unique objects by field value
INLINE_CODE_48
Reduce array to single value (sum example)
INLINE_CODE_49
Recursively find all numbers
INLINE_CODE_50
Use default value if field is null/missing
INLINE_CODE_51
Error handling with fallback
INLINE_CODE_52
Flatten nested arrays one level
INLINE_CODE_53
Flatten nested arrays N levels
INLINE_CODE_54
Add or update fields
INLINE_CODE_55
Delete field from object
INLINE_CODE_56
Delete element from array by index
INLINE_CODE_57
Convert object to key-value pairs array
INLINE_CODE_58
Convert key-value pairs to object
INLINE_CODE_59
Transform all object values
INLINE_CODE_60
Filter and collect into new array
INLINE_CODE_61
Get minimum value from array
INLINE_CODE_62
Get maximum value from array
INLINE_CODE_63
Get object with minimum field value
INLINE_CODE_64
Get object with maximum field value
INLINE_CODE_65
Sum array of numbers or concatenate strings
INLINE_CODE_66
Check if any element matches condition
INLINE_CODE_67
Check if all elements match condition
String Operations
Command
Description
INLINE_CODE_68
String interpolation
INLINE_CODE_69
Convert value to string
INLINE_CODE_70
Convert string to number
INLINE_CODE_71
Split string into array
INLINE_CODE_72
Join array elements into string
INLINE_CODE_73
Check if string starts with prefix
INLINE_CODE_74
Check if string ends with suffix
INLINE_CODE_75
Check if string contains substring
INLINE_CODE_76
Remove prefix from string
INLINE_CODE_77
Remove suffix from string
INLINE_CODE_78
Convert string to lowercase
INLINE_CODE_79
Convert string to uppercase
INLINE_CODE_80
Test if string matches regex
INLINE_CODE_81
Get regex match details
INLINE_CODE_82
Capture named regex groups
INLINE_CODE_83
Replace first occurrence
INLINE_CODE_84
Replace all occurrences
Configuración
Command-Line Options
# Raw output (no JSON quotes for strings)
jq -r '.field' file.json
# Compact output (single line)
jq -c '.' file.json
# Sort object keys
jq -S '.' file.json
# Slurp mode (read entire input into array)
jq -s '.' file1.json file2.json
# Null input (don't read stdin)
jq -n '{created: now}'
# Exit status based on output
jq -e '.field' file.json # Exit 1 if false/null
# Color output control
jq -C '.' file.json # Force color
jq -M '.' file.json # Disable color
# Custom indentation
jq --indent 4 '.' file.json
jq --tab '.' file.json
# Read filter from file
jq -f filter.jq data.json
# Pass variables to jq
jq --arg name "John" '{user: $name}' -n
jq --argjson count 42 '{total: $count}' -n
jq --slurpfile data file.json '{imported: $data}' -n
# Multiple inputs
jq --jsonargs '. | @json' --args arg1 arg2 arg3
Environment Variables
# Customize output colors (format: null:false:true:numbers:strings:arrays:objects)
export JQ_COLORS = "0;90:0;91:0;92:0;93:0;94:0;95:0;96"
# Default colors (bright theme)
export JQ_COLORS = "1;30:0;39:0;39:0;39:0;32:1;39:1;39"
# Disable colors entirely
export NO_COLOR = 1
Filtros Archivos
Crear archivos de filtro reutilizables para operaciones complejas:
# filter.jq
.data[]
| select ( .status == "active" )
| {
id: .id,
name: .name,
created: .timestamp | strftime( "%Y-%m-%d" )
}
# Usage
jq -f filter.jq data.json
Common Use Cases
Caso de uso: Parse API Response
# Extract specific fields from API response
curl -s https://api.example.com/users | jq '.users[] | {name: .name, email: .email}'
# Filter active users and get their IDs
curl -s https://api.example.com/users | jq -r '.users[] | select(.active == true) | .id'
# Count total results
curl -s https://api.example.com/users | jq '.users | length'
Use Case: Process AWS CLI Output
# List EC2 instance IDs and names
aws ec2 describe-instances | jq -r '.Reservations[].Instances[] | "\(.InstanceId) \(.Tags[]|select(.Key=="Name")|.Value)"'
# Get S3 bucket sizes
aws s3api list-buckets | jq -r '.Buckets[].Name' | while read bucket; do
aws s3 ls s3://$bucket --recursive --summarize | grep "Total Size" | jq -R ". | {bucket: \" $bucket \", size: .}"
done
# Filter running instances
aws ec2 describe-instances | jq '.Reservations[].Instances[] | select(.State.Name == "running")'
Use Case: Log Analysis
# Parse JSON logs and extract errors
cat application.log | jq -r 'select(.level == "ERROR") | "\(.timestamp) \(.message)"'
# Count log entries by level
cat application.log | jq -s 'group_by(.level) | map({level: .[0].level, count: length})'
# Find slow requests (response time > 1000ms)
cat access.log | jq 'select(.response_time > 1000) | {path: .path, time: .response_time}'
# Convert flat structure to nested
echo '[{"id":1,"name":"John","dept":"IT"},{"id":2,"name":"Jane","dept":"HR"}]' | \
jq 'group_by(.dept) | map({department: .[0].dept, employees: map({id: .id, name: .name})})'
# Merge multiple JSON files
jq -s 'add' file1.json file2.json file3.json
# Create CSV from JSON
jq -r '.[] | [.id, .name, .email] | @csv' data.json
Caso de uso: Gestión de configuración
# Extract specific config value
jq -r '.database.host' config.json
# Update config value
jq '.database.port = 5432' config.json > config.tmp && mv config.tmp config.json
# Merge config files
jq -s '.[0] * .[1]' base-config.json override-config.json > final-config.json
# Validate required fields exist
jq -e '.database.host and .database.port' config.json && echo "Valid" || echo "Invalid"
Buenas prácticas
Use -r para scripts : Al extraer valores para scripts de shell, utilice salida cruda para evitar cadenas citadas
Pipa eficientemente Operaciones de cadena con __INLINE_CODE_86_ en lugar de múltiples jq requiere un mejor rendimiento
Meta filtros incrementalmente : Construir filtros complejos paso a paso, probar cada parte con datos de muestra
Los campos perdidos Uso // operador o try-catch para proporcionar defectos para campos opcionales
Use -e para validación : Establecer el estado de salida basado en la salida para el manejo de errores confiable en scripts
Filtros complejos enteros: Guardar los filtros reutilizables en los archivos .jq y utilizar -f opción para mantener
¿Qué? Filtros jq únicos en cáscara para evitar la expansión de cáscaras de caracteres especiales
Use select antes __INLINE_CODE_93_ : Filtrar datos antes de transformarse para mejorar el rendimiento en grandes conjuntos de datos
Leverage --arg para seguridad : Pasar valores externos como argumentos en lugar de interpolación de cadenas para prevenir la inyección
Profile de grandes operaciones : Use --debug bandera para entender la ejecución de filtros y optimizar los cuellos de botella
Troubleshooting
Issue
Solution
INLINE_CODE_96
Check JSON syntax - likely missing quotes around strings or trailing commas
INLINE_CODE_97
Verify filter syntax - ensure proper pipe usage and bracket matching
Output shows INLINE_CODE_98 unexpectedly
Field doesn't exist - use INLINE_CODE_99 or INLINE_CODE_100 to check first
INLINE_CODE_101
Trying to access object field on array - use INLINE_CODE_102 to iterate or INLINE_CODE_103 for specific index
INLINE_CODE_104
Input is null or empty - use INLINE_CODE_105 flag or check input source
Colors not showing in output
Pipe to INLINE_CODE_106 or use INLINE_CODE_107 to force color output
INLINE_CODE_108
Install jq using package manager or download from URL_164
Very slow performance on large files
Use streaming parser with INLINE_CODE_109 or filter early in pipeline
Special characters breaking filter
Wrap entire filter in single quotes and escape internal single quotes with INLINE_CODE_110
Need to process multiple JSON objects (not array)
Use INLINE_CODE_111 to slurp into array or process line-by-line with INLINE_CODE_112
Error: INLINE_CODE_113 or INLINE_CODE_114 outside loop
These keywords only work inside INLINE_CODE_115 /INLINE_CODE_116 loops - restructure logic
Memory issues with large datasets
Use streaming mode INLINE_CODE_117 or process in chunks with INLINE_CODE_118
Quick Referencia: Operadores
Operator
Description
Example
INLINE_CODE_119
Identity / current value
INLINE_CODE_120
INLINE_CODE_121
Object field access
INLINE_CODE_122
INLINE_CODE_123
Array index access
INLINE_CODE_124
INLINE_CODE_125
Array/object iteration
INLINE_CODE_126
INLINE_CODE_127
Pipe (chain operations)
INLINE_CODE_128
INLINE_CODE_129
Multiple outputs
INLINE_CODE_130
INLINE_CODE_131
Alternative operator
INLINE_CODE_132
INLINE_CODE_133
Optional operator (suppress errors)
INLINE_CODE_134
INLINE_CODE_135
Addition / concatenation
INLINE_CODE_136
INLINE_CODE_137
Subtraction / array difference
INLINE_CODE_138
INLINE_CODE_139
Multiplication / object merge
INLINE_CODE_140
INLINE_CODE_141
Division
INLINE_CODE_142
INLINE_CODE_143
Modulo
INLINE_CODE_144
INLINE_CODE_145
Equality
INLINE_CODE_146
INLINE_CODE_147
Inequality
INLINE_CODE_148
INLINE_CODE_149 , INLINE_CODE_150 , INLINE_CODE_151 , INLINE_CODE_152
Comparisons
INLINE_CODE_153
and, or_ , not__ ___ Los operadores lógicos son insostenibles jq '.a and .b'