Ale*_*chi 5 select json edit jq
我对命令 jq 真的很陌生,我正在尝试进行一些过滤以删除我不想要/不需要的数据块。
这是我的 JSON 结构示例:
{
"BackupCfg": [
{
"type": "filesystem",
"repository": "trunk",
"url": "test.example.com",
"port": "394",
"cfg": [
{
"Default": "true",
"ID": "trunk00",
"Paths": [
"/etc",
"/home",
"/var",
"/usr/local",
"/opt",
"/root"
],
"Cron": "33 0 * * *"
}
]
},
{
"type": "filesystem",
"repository": "trunk02",
"url": "test.example.com",
"port": "394",
"cfg": [
{
"ID": "trunk01",
"Paths": [
"/opt/example",
"/opt/var_example"
],
"Cron": "*/30 0-23 * * *"
}
]
},
{
"type": "database",
"repository": "trunk-db",
"url": "test.example.com",
"port": "399",
"cfg": [
{
"Default": "true",
"ID": "trunk00",
"db_type": "mysql",
"db_hostname": "localhost",
"db_port": "3306",
"db_user": "root",
"db_pwd": "password",
"databases": [],
"Cron": "40 0 * * *"
},
{
"ID": "trunk01",
"db_type": "mysql",
"db_hostname": "localhost",
"db_port": "3307",
"db_user": "riit",
"db_pwd": "passwird",
"databases": [],
"Cron": "33 3 * * *"
},
{
"Default": "false",
"ID": "trunk02",
"db_type": "postgres",
"db_hostname": "localhost",
"db_port": "3308",
"db_user": "ruut",
"db_pwd": "passwurd",
"databases": [],
"Cron": "0 10 * * *"
}
]
}
]
}
Run Code Online (Sandbox Code Playgroud)
我想过滤它以便只有“类型”:“文件系统”,并获得以下输出:
{
"BackupCfg": [
{
"type": "filesystem",
"repository": "trunk",
"url": "test.example.com",
"port": "394",
"cfg": [
{
"Default": "true",
"ID": "trunk00",
"Paths": [
"/etc",
"/home",
"/var",
"/usr/local",
"/opt",
"/root"
],
"Cron": "33 0 * * *"
}
]
},
{
"type": "filesystem",
"repository": "trunk02",
"url": "test.example.com",
"port": "394",
"cfg": [
{
"ID": "trunk01",
"Paths": [
"/opt/example",
"/opt/var_example"
],
"Cron": "*/30 0-23 * * *"
}
]
}
]
}
Run Code Online (Sandbox Code Playgroud)
我尝试了一些命令,例如
jq '.[][] | select(.type | contains("filesystem"))'
Run Code Online (Sandbox Code Playgroud)
但它破坏了原有的结构。
我四处搜索,找到了很多例子,但很多都不起作用,或者没有给我我需要的东西。
有人有什么想法吗?如果有人也有任何好的学习网站来理解jq,那就太棒了!
提前致谢!
jq 解决方案:
jq '.BackupCfg |= map(select(.type == "filesystem"))' file.json
Run Code Online (Sandbox Code Playgroud)
输出:
{
"BackupCfg": [
{
"type": "filesystem",
"repository": "trunk",
"url": "test.example.com",
"port": "394",
"cfg": [
{
"Default": "true",
"ID": "trunk00",
"Paths": [
"/etc",
"/home",
"/var",
"/usr/local",
"/opt",
"/root"
],
"Cron": "33 0 * * *"
}
]
},
{
"type": "filesystem",
"repository": "trunk02",
"url": "test.example.com",
"port": "394",
"cfg": [
{
"ID": "trunk01",
"Paths": [
"/opt/example",
"/opt/var_example"
],
"Cron": "*/30 0-23 * * *"
}
]
}
]
}
Run Code Online (Sandbox Code Playgroud)
https://stedolan.github.io/jq/manual/v1.5/#select(boolean_expression)
| 归档时间: |
|
| 查看次数: |
759 次 |
| 最近记录: |