2017-10-28 18 views
-3

私は平らなテーブルを持っています。私はそれをネストされたjson形式に変換したい。Pythonで階層化テーブルを階層型のjsonに変換する方法は?

database  schema table_name   col_name 

exploration dbo TestTable   name 
exploration dbo TestTable   last_name 
exploration dbo Table_1    name 
exploration dbo Table_1    d_id 
exploration dbo tblMonitorChange EventType 
exploration dbo tblMonitorChange SchemaName 
exploration dbo tblMonitorChange ObjectName 
exploration dbo tblMonitorChange ObjectType 
exploration dbo tblMonitorChange EventDate 
exploration dbo tblMonitorChange SystemUser 
exploration dbo tblMonitorChange CurrentUser 
exploration dbo tblMonitorChange OriginalUser 
ReportServer dbo Users    UserID 
ReportServer dbo Users    Sid 
ReportServer dbo Users    UserType 
ReportServer dbo Users    AuthType 
ReportServer dbo Users    UserName 
ReportServer dbo Users    ServiceToken 
ReportServer dbo Users    Setting 

私は一般的な解決策を探していますが、列名をハードコーディングするのではありません。

助けていただければ幸いです。

答えて

0

私はこの問題を再帰的に解決しました。この機能は、テストされ、動作します:

def table_to_json(model): 
    print('-------------------------------------------------------------') 
    doc = {}; 
    col_names = list(model.columns) 
    grouped = model.groupby(col_names[0])[col_names[1]] 
    values = grouped.apply(lambda x: set(x.tolist())) 
    a = values.shape 
    if(len(col_names)==2): 
     return dict(values) 
    keys = list(grouped.groups.keys()) 
    for k in keys: 
     doc.update({k:table_to_json(model[model[col_names[0]] == k][col_names[1:]])}) 

    return doc 

それは、入力として(私の最初の記事でそれを確認してください)データフレームを受け取り、出力として辞書ドキュメントを返します。これは出力の一部です:

{'exploration': {'dbo': {'Table_1': {'d_id', 'name'}, 
    'TestTable': {'last_name', 'name'}, 
    'tblMonitorChange': {'CurrentUser', 
    'EventDate', 
    'EventType', 
    'ObjectName', 
    'ObjectType', 
    'OriginalUser', 
    'SchemaName', 
    'SystemUser'}}}, 
'ReportServer': {'dbo': {'ActiveSubscriptions': {'ActiveID', 
    'SubscriptionID', 
    'TotalFailures', 
    'TotalNotifications', 
    'TotalSuccesses'}, 
    'Batch': {'Action', 
    'AddedOn', 
    'BatchID', 
    'BoolParam', 
    'Content', 
    'Item', 
    'Param', 
    'Parent', 
    'Properties'}}}}