如何使用 jq(或 python)删除某些 JSON 中的特定键(?)?
How to use jq (or python) to remove a particular key(?) in some JSON?
这里是输入json。它是从 Red Hat Satellite 中提取的 puppet class 的部分 JSON 转储。
{
"Id": 9999,
"Match": "fqdn=server.fqdn.com",
"Value": {
"user1": {
"order": 90,
"nofile": {
"comment": "I want to lose this comment",
"soft": "65535",
"hard": "65535"
},
"nproc": {
"comment": "I want to lose this also",
"soft": "32768",
"hard": "32768"
}
},
"user2": {
"order": 90,
"nofile": {
"comment": "I want to lose this comment",
"soft": "65535",
"hard": "65535"
},
"nproc": {
"comment": "I want to lose this also",
"soft": "32768",
"hard": "32768"
}
}
}
}
我想删除所有的“评论”。我找不到执行此操作的示例,也找不到对一般执行此操作的解释。或者我太笨了,无法理解我目前所读的内容。
所以我的输出是
{
"Id": 9999,
"Match": "fqdn=server.fqdn.com",
"Value": {
"user1": {
"order": 90,
"nofile": {
"soft": "65535",
"hard": "65535"
},
"nproc": {
"soft": "32768",
"hard": "32768"
}
},
"user2": {
"order": 90,
"nofile": {
"soft": "65535",
"hard": "65535"
},
"nproc": {
"soft": "32768",
"hard": "32768"
}
}
}
}
有人要吗?
del( .. | objects | .comment )
Demo 在 jqplay
在 Python 中,它看起来像这样:
def remove_comments(node):
if isinstance(node, dict):
if 'comment' in node:
del node['comment']
for child in node.values():
remove_comments(child)
elif isinstance(node, list):
for child in node:
remove_comments(child)
这里是输入json。它是从 Red Hat Satellite 中提取的 puppet class 的部分 JSON 转储。
{
"Id": 9999,
"Match": "fqdn=server.fqdn.com",
"Value": {
"user1": {
"order": 90,
"nofile": {
"comment": "I want to lose this comment",
"soft": "65535",
"hard": "65535"
},
"nproc": {
"comment": "I want to lose this also",
"soft": "32768",
"hard": "32768"
}
},
"user2": {
"order": 90,
"nofile": {
"comment": "I want to lose this comment",
"soft": "65535",
"hard": "65535"
},
"nproc": {
"comment": "I want to lose this also",
"soft": "32768",
"hard": "32768"
}
}
}
}
我想删除所有的“评论”。我找不到执行此操作的示例,也找不到对一般执行此操作的解释。或者我太笨了,无法理解我目前所读的内容。
所以我的输出是
{
"Id": 9999,
"Match": "fqdn=server.fqdn.com",
"Value": {
"user1": {
"order": 90,
"nofile": {
"soft": "65535",
"hard": "65535"
},
"nproc": {
"soft": "32768",
"hard": "32768"
}
},
"user2": {
"order": 90,
"nofile": {
"soft": "65535",
"hard": "65535"
},
"nproc": {
"soft": "32768",
"hard": "32768"
}
}
}
}
有人要吗?
del( .. | objects | .comment )
Demo 在 jqplay
在 Python 中,它看起来像这样:
def remove_comments(node):
if isinstance(node, dict):
if 'comment' in node:
del node['comment']
for child in node.values():
remove_comments(child)
elif isinstance(node, list):
for child in node:
remove_comments(child)