You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用jq过滤JSON并保留原始结构?

Fixing jq Filtering to Preserve JSON Structure & Keep Only "filesystem" Entries

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_devices targets 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 object
  • map(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.

  • Official jq Manual: Just run man jq in 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 10:13:46