python - python json从找到的元素中捕获整个节点
问题描述
我正在加载 json 并尝试提取一部分。我可以很好地加载json并查询它。我坚持检索它在其中找到的 json 节点。
所以我有一个像下面这样的 json 结构。我将如何寻找一个元素并捕获它的整个节点。即 name="7004389c-c47a-4611-9bd7-9f5dfe051d17" 然后返回以下内容: OUTPUT 示例:
{
"name": "7004389c-c47a-4611-9bd7-9f5dfe051d17",
"children": [],
"behaviors": [
{
"name": "xxx",
"options": {
"key": "xxx-xxx-xxx-xxx",
"compress": true,
"ports": ""
}
}
],
"criteria": [
{
"name": "xxxx",
"options": {
"Name": "UUID",
"values": [
"7004389c-c47a-4611-9bd7-9f5dfe051d17"
]
}
}
],
"criteriaMustSatisfy": "all"
}
JSON 示例:
"etag": "14b3796c268c87553291702c808e86dfe1e53d1b",
"rules": {
"name": "default",
"children": [
{
"name": "xxxx",
"children": [
{
"name": "dffaa42b-3f0f-425f-a9a1-a63cd35b2517",
"children": [],
"behaviors": [
{
"name": "xxx",
"options": {
"key": "xxx-xxx-xxx-xxx",
"compress": true,
"ports": ""
}
}
],
"criteria": [
{
"name": "xxxx",
"options": {
"Name": "UUID",
"values": [
"dffaa42b-3f0f-425f-a9a1-a63cd35b2517"
]
}
}
],
"criteriaMustSatisfy": "all"
},
{
"name": "7004389c-c47a-4611-9bd7-9f5dfe051d17",
"children": [],
"behaviors": [
{
"name": "xxx",
"options": {
"key": "xxx-xxx-xxx-xxx",
"compress": true,
"ports": ""
}
}
],
"criteria": [
{
"name": "xxxx",
"options": {
"Name": "UUID",
"values": [
"7004389c-c47a-4611-9bd7-9f5dfe051d17"
]
}
}
],
"criteriaMustSatisfy": "all"
}
],
"behaviors": [],
"criteria": [],
"criteriaMustSatisfy": "all"
}
],
"behaviors": [
{
"name": "xxx",
"options": {}
}
],
"options": {
"is_secure": true
},
"variables": []
},
"warnings": [
],
"Format": "xxx"
}
解决方案
您可以根据以下键搜索特定字典name
:
# assuming test contains your json data
key = '7004389c-c47a-4611-9bd7-9f5dfe051d17'
res = [node for node in test["rules"]["children"][0]['children'] if node['name'] == key][0]
输出:
{'name': '7004389c-c47a-4611-9bd7-9f5dfe051d17', 'children': [], 'behaviors': [{'name': 'xxx', 'options': {'key': 'xxx-xxx-xxx-xxx', 'compress': True, 'ports': ''}}], 'criteria': [{'name': 'xxxx', 'options': {'Name': 'UUID', 'values': ['7004389c-c47a-4611-9bd7-9f5dfe051d17']}}], 'criteriaMustSatisfy': 'all'}
推荐阅读
- javascript - 即使谷歌图表中的值为零,如何显示一个小条?
- html - 如何使用标签来显示特定用户的信息,而不仅仅是第一个
- windows - 使用 Powershell 查找最新创建的 JSON
- javascript - 我可以通过chrome浏览器制作页面的部分截图吗?
- android - 此处 Maps Android SDK 调用 PositioningManager 启动方法返回 false
- terraform - 如何使用 cloud-init 和 Terraform 设置主机名?
- php - 不小心删除了关系laravel
- python - 从 1-dim 位数组中获取特定的 2-dim 数组序列 [Python]
- angular - 尝试在使用角度 7 中的拦截器刷新令牌后重复 http 请求
- javascript - Javascript 上的滑块未按预期工作