如何使用jq过滤JSON并保留原始结构?
Hey there! Let's tackle this jq problem step by step—no more broken structures, promise.
First, let's assume a common example of your original JSON structure (adjust if yours is different, but the core logic stays the same):
{ "storage_devices": [ {"type": "filesystem", "mount_point": "/", "size": "50GB"}, {"type": "network", "mount_point": "/mnt/cloud", "size": "1TB"}, {"type": "filesystem", "mount_point": "/home", "size": "200GB"} ], "system_info": {"last_scanned": "2024-05-20", "status": "healthy"} }
The Correct jq Command to Preserve Structure
To keep the entire original JSON structure but only retain entries where type is "filesystem" in the storage_devices array, use this command:
jq '.storage_devices |= map(select(.type == "filesystem"))' your-input.json
Breakdown of what this does:
.storage_devicestargets the specific array you want to filter (replace with your actual array key if it’s named differently)|=tells jq to update that array in-place instead of replacing the entire JSON objectmap(select(.type == "filesystem"))iterates over the array and keeps only items that match your condition
If your JSON is a top-level array (no outer object), like this:
[ {"type": "filesystem", "path": "/tmp"}, {"type": "network", "path": "/srv/ftp"} ]
Simplify the command to:
jq 'map(select(.type == "filesystem"))' your-input.json
This returns a filtered array, preserving the top-level array structure perfectly.
Why Your Previous Command Broke the Structure
Chances are you used something like jq 'select(.type == "filesystem")' directly on an object with multiple top-level keys. That command would discard everything except the matching entries, wiping out other critical parts of your JSON. Using |= to update specific fields instead of replacing the whole document fixes this issue.
Great jq Learning Resources (No External Links Needed!)
- Official jq Manual: Just run
man jqin your terminal—it’s packed with syntax explanations, real-world examples, and advanced features. Perfect for quick reference when you’re stuck. - jq Cookbook: Community-curated collections of common jq tasks (filtering, transforming, merging JSON) with step-by-step commands. You can find these in markdown form in open-source repos or offline documentation.
- Interactive Practice: Use local tools or offline playgrounds to test jq commands in real-time. Many code editors have jq plugins that let you preview results as you type, making it easy to experiment without breaking anything.
内容的提问来源于stack exchange,提问作者Alessandro Perucchi

