看起来你的代码片段没有完整,特别是`build_department_tree`函数的部分。我将帮助你完成这个函数,并解释它的功能。
以下是完整的代码实现:
```python
import requests
import json
import pandas as pd
# Function to remove unwanted fields from a dictionary
def remove_unwanted_fields(data, fields_to_remove):
if isinstance(data, dict):
return {k: remove_unwanted_fields(v, fields_to_remove) for k, v in data.items() if k not in fields_to_remove}
elif isinstance(data, list):
return [remove_unwanted_fields(item, fields_to_remove) for item in data]
else:
return data
# Function to filter departments and personnel by isBusiness == true
def filter_by_is_business(items):
return [item for item in items if item.get("isBusiness") == True]
# Function to build department hierarchy tree
def build_department_tree(departments):
department_map = {dept["id"]: {"data": dept, "children": []} for dept in departments}
root_nodes = []
for dept in departments:
parent_id = dept.get("parent")
if parent_id is None or parent_id not in department_map:
root_nodes.append(department_map[dept["id"]])
else:
department_map[parent_id]["children"].append(department_map[dept["id"]])
return [node["data"] for node in root_nodes]
# Example usage
if __name__ == "__main__":
# Mock data
departments = [
{"id": 1, "name": "HR", "parent": None, "isBusiness": False},
{"id": 2, "name": "Engineering", "parent": None, "isBusiness": True},
{"id": 3, "name": "Team A", "parent": 2, "isBusiness": True},
{"id": 4, "name": "Team B", "parent": 2, "isBusiness": False},
]
filtered_departments = filter_by_is_business(departments)
print("Filtered Departments:", filtered_departments)
department_tree = build_department_tree(filtered_departments)
print("Department Tree:", json.dumps(department_tree, indent=4))
```
### 解释
1. **`remove_unwanted_fields`**:
- 这个函数递归地从字典或列表中移除指定的字段。
- 如果传入的是字典,则检查键是否在需要移除的字段列表中。如果不在,则保留该键值对,并递归处理值。
- 如果传入的是列表,则对列表中的每个元素递归调用该函数。
2. **`filter_by_is_business`**:
- 这个函数过滤出`isBusiness`为`True`的部门或人员。
3. **`build_department_tree`**:
- 这个函数构建一个部门的层级结构树。
- 首先创建一个字典`department_map`,其中键是部门ID,值是一个包含部门信息和子部门列表的字典。
- 然后遍历所有部门,根据父级ID将子部门添加到父部门的子部门列表中。
- 最后返回根节点的部门信息。
### 输出示例
假设我们有以下数据:
```python
departments = [
{"id": 1, "name": "HR", "parent": None, "isBusiness": False},
{"id": 2, "name": "Engineering", "parent": None, "isBusiness": True},
{"id": 3, "name": "Team A", "parent": 2, "isBusiness": True},
{"id": 4, "name": "Team B", "parent": 2, "isBusiness": False},
]
```
运行上述代码后,输出如下:
```
Filtered Departments: [{'id': 2, 'name': 'Engineering', 'parent': None, 'isBusiness': True}, {'id': 3, 'name': 'Team A', 'parent': 2, 'isBusiness': True}]
Department Tree: [
{
"id": 2,
"name": "Engineering",
"parent": null,
"isBusiness": true
}
]
```
###