将组织结构转换为树状json
Posted 雅虎跳跳
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了将组织结构转换为树状json相关的知识,希望对你有一定的参考价值。
# -*-coding:utf8-*- import pymysql import datetime import json import random import logging logging.basicConfig(filename="test_convert_org_to_tree.log",filemode="a", format="%(asctime)s-%(funcName)s-%(lineno)d-%(levelname)s:%(message)s",level=logging.INFO) console = logging.StreamHandler() logging.getLogger().addHandler(console) def execute_sql(sqlstr): db = pymysql.connect("10.136.142.111","liumin1","liumin1","liumin1",port=3306 ) cursor = db.cursor() try: cursor.execute(sqlstr) if(sqlstr.lower().startswith("select")): data = cursor.fetchall() db.commit() except Exception as e: logging.info(e) logging.info("执行失败的SQL是:%s" % sqlstr) db.rollback() db.close() try: return data except Exception as e: return None # def convert_table_to_org(data_list): # org = {} # org["id"] = data_list[0] # org["name"] = data_list[1] # org["parentid"] = data_list[2] # return org def consalt_table_to_python(sqlstr): logging.info("要执行的SQL是:%s" % sqlstr) data = execute_sql(sqlstr) # if(not data): # return org_list = [] logging.info("data是:%s" % json.dumps(data)) for i in data: org = {} org["id"] = i[0] org["name"] = i[1] org["parentid"] = i[2] org_list.append(org) return org_list def get_sub_children(org_tree): sqlstr = "select id,name,parentid from liuyue_test_org where parentid=%d;" %org_tree["id"] org_tree_tmp = consalt_table_to_python(sqlstr) logging.info("org_tree_tmp是:%s" % org_tree_tmp) # if(org_tree_tmp): for i in org_tree_tmp: logging.info("i是:%s" % i) get_sub_children(i) org_tree["childrenlist"]=org_tree_tmp def convert_org_to_tree(): sqlstr = "select id,name,parentid from liuyue_test_org where parentid=0;" org_tree = consalt_table_to_python(sqlstr)[0] get_sub_children(org_tree) return (json.dumps(org_tree)) print(convert_org_to_tree())
以上是关于将组织结构转换为树状json的主要内容,如果未能解决你的问题,请参考以下文章
如何将树状的数组和对象的嵌套数据结构转换为具有计算/计数 id 和跟踪父 id 的项目列表?
Javascript中扁平化数据结构与JSON树形结构转换详解
如何解决 NodeJS 中的“TypeError:将循环结构转换为 JSON”