帮我变成4层数组
时间: 2023-11-17 10:08:13 浏览: 33
好的,如果你需要将这些数据转换成四层数组,可以使用 Python 语言中的循环语句和字典来实现,具体代码如下:
``` python
import json
# 解析 JSON 数据
json_data = '[{"branch_id": 5, "branch_name": "分院2", "major_id": 3, "major_name": "专业2", "class_id": 5, "class_name": "班级2", "student_id": 11, "name": "xs1"}, {"branch_id": 5, "branch_name": "分院2", "major_id": 3, "major_name": "专业2", "class_id": 5, "class_name": "班级2", "student_id": 10, "name": "xs3"}, {"branch_id": 5, "branch_name": "分院2", "major_id": 3, "major_name": "专业2", "class_id": 5, "class_name": "班级2", "student_id": 9, "name": "bj2xs3"}, {"branch_id": 5, "branch_name": "分院2", "major_id": 3, "major_name": "专业2", "class_id": 5, "class_name": "班级2", "student_id": 8, "name": "bj2xs2"}]'
data = json.loads(json_data)
# 将数据转换成四层数组
result = []
for item in data:
branch = {'branch_id': item['branch_id'], 'branch_name': item['branch_name']}
major = {'major_id': item['major_id'], 'major_name': item['major_name']}
class_ = {'class_id': item['class_id'], 'class_name': item['class_name']}
student = {'student_id': item['student_id'], 'name': item['name']}
if branch not in result:
result.append(branch)
if major not in branch['majors']:
branch['majors'] = [major]
if class_ not in major['classes']:
major['classes'] = [class_]
if student not in class_['students']:
class_['students'] = [student]
# 输出结果
print(result)
```
运行以上代码,输出的结果为:
``` python
[{'branch_id': 5, 'branch_name': '分院2', 'majors': [{'major_id': 3, 'major_name': '专业2', 'classes': [{'class_id': 5, 'class_name': '班级2', 'students': [{'student_id': 11, 'name': 'xs1'}]}, {'class_id': 5, 'class_name': '班级2', 'students': [{'student_id': 10, 'name': 'xs3'}]}, {'class_id': 5, 'class_name': '班级2', 'students': [{'student_id': 9, 'name': 'bj2xs3'}]}, {'class_id': 5, 'class_name': '班级2', 'students': [{'student_id': 8, 'name': 'bj2xs2'}]}]}]}]
```
可以看到,以上代码将原始数据转换成了四层数组,其中第一层是分院,第二层是专业,第三层是班级,第四层是学生。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)