Python对MySQL中读取的数据进行json化

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u012111465/article/details/85002136

对MySQL中读取的数据进行json化

数据格式:

((cluster1,db1,tb1), (cluster1,db1,tb2), (cluster1,db1,tb3), (cluster1,db2,tb3), (cluster2,db3,tb5), (cluster3,db4,tb6), (cluster3,db5,tb7), (cluster3,db5,tb8), (cluster4,db6,tb9), (cluster4,db6,tb10))

建立成的目标JSON格式:

{
  cluster1: [
    {
      db1: [tb1, tb2, .....],
      db2: [tb1, tb2, .....],
      db3: [tb1, tb2, .....]
    }
  ]
}

python code

result = (('cluster1','db1','tb1'), ('cluster1','db1','tb2'), ('cluster1','db1','tb3'), ('cluster1','db2','tb3'), ('cluster2','db3','tb5'), ('cluster3','db4','tb6'), ('cluster3','db5','tb7'), ('cluster3','db5','tb8'), ('cluster4','db6','tb9'), ('cluster4','db6','tb10'))
try:
    data = {}
    db = {}
    db_values = []
    for xxp in result:
        db_keys = db.keys()
        if xxp[1] in db_keys:
            db_values.append(xxp[-1])
        else:
            db_values = []
            db_values.append(xxp[-1])
        ck_keys = data.keys()
        if xxp[0] in ck_keys:
            db[xxp[1]] = db_values
            data[xxp[0]] = db        
        else:
            db = {}
            db[xxp[1]] = db_values
            data[xxp[0]] = db
    # data = [dict(zip(data_keys ,xq)) for xq in result]
except Exception as e:
    print e
body = {
           "code":"200",
           "status":"调用成功",
           "data":data
       }    

输出JSON结果:

{
    'status': '调用成功', 
    'code': '200', 
    'data': {
        'cluster2': {'db3': ['tb5']}, 
        'cluster3': {'db5': ['tb7', 'tb8'], 'db4': ['tb6']}, 
        'cluster1': {'db1': ['tb1', 'tb2', 'tb3'], 'db2': ['tb3']},
        'cluster4': {'db6': ['tb9', 'tb10']}
    }
} 

猜你喜欢

转载自blog.csdn.net/u012111465/article/details/85002136