目錄樹轉 JSON

巫樂發表於2020-01-07

背景:為了處理2處不同來源的資料,就都轉換成json集合,方便操作。

目錄樹結構

----demo\
    |----v1\
    |    |----init\
    |    |    |----time.py
    |    |----order.py
    |    |----surface\
    |    |    |----detail.py
    |    |    |----order.py
    |    |    |----user.py
    |    |----user.py
    |----v2\
    |    |----country.py
    |    |----list.py
    |----v3\
    |    |----languages.py
    |    |----surface\
    |    |    |----detail.py
    |    |    |----list.py
    |    |----user.py

以上是目錄結構 首先進行讀取,放到一個列表裡,在讀取的時候,還進行了正則匹配,匹配對應的py檔案,以及檔案內部的 方法。並且內部匹配到的每一條 方法生成一條記錄

import sys
from pathlib import Path
import json
import re

tree_str = ''
tree_list = []

def generate_tree(pathname, n=0):
    global tree_str
    global tree_list
    if pathname.is_file():
        temp_file_name = pathname.name
        temp_file_name_list = temp_file_name.split('.')
        if len(temp_file_name_list) == 2 and temp_file_name_list[1] == 'py':
            file = open(pathname, 'r', encoding='utf-8')
            temp_action = []
            for line in file.readlines():
                line = line.strip()
                strName = getStrName(pathname.parent, temp_file_name_list[0])
                matchObj = re.match('def getAction()', line)
                if matchObj:
                    temp_action.append('get')

                matchObj = re.match('def postAction()', line)
                if matchObj:
                    temp_action.append('post')

                matchObj = re.match('def putAction()', line)
                if matchObj:
                    temp_action.append('put')

                matchObj = re.match('def deleteAction()', line)
                if matchObj:
                    temp_action.append('delete')
            if len(temp_action) > 0:
                temp_strName = strName + ',' + '_'.join(temp_action)
                tree_list.append(temp_strName.lower())
    elif pathname.is_dir():
        for cp in pathname.iterdir():
            generate_tree(cp, n + 1)

def getStrName(pathname, strName):
    if pathname.name != 'demo':
        strName = pathname.name + '/' + strName
        strName = getStrName(pathname.parent,strName)
    return strName

if __name__ == '__main__':
    p = Path(r'E:\www\myleetcode\demo')
    generate_tree(p)
    tree_list.sort()
    print(tree_list)

執行結果

['v1/init/time,get', 'v1/order,get', 'v1/surface/detail,post_get', 'v1/surface/order,post', 'v1/surface/user,post', 'v1/user,get', 'v2/country,put', 'v2/list,put', 'v3/languages,get', 'v3/surface/detail,delete', 'v3/surface/list,delete', 'v3/user,get']

以上生成了初步的記錄,接下來就是轉換成想要的json格式

轉json

塞到字典裡

    temp = {}
    for api in tree_list:
        temp_split = api.split('/')
        if len(temp_split) == 2:
            temp_str = temp_split[1].split(',')
            temp_api = {temp_str[0] : temp_str[1]}
            if temp_split[0] not in temp:
                temp[temp_split[0]] = temp_api
            else:
                temp[temp_split[0]].update(temp_api)
        elif len(temp_split) == 3:
            temp_str = temp_split[2].split(',')
            temp_api = {temp_str[0] : temp_str[1]}
            if  temp_split[0] not in temp:
                temp_surface = {temp_split[1] : temp_api}
                temp[temp_split[0]] = temp_surface
            else:
                temp_surface = temp[temp_split[0]]
                if temp_split[1] not in temp_surface:
                    temp_surface.update({temp_split[1]: temp_api})
                else:
                    temp_api_list = temp_surface[temp_split[1]]
                    temp_api_list.update(temp_api)
                    temp_surface[temp_split[1]] = temp_api_list
                temp[temp_split[0]] = temp_surface

    str_json = json.dumps(temp)
    print (str_json)

json結果

{"v1": {"init": {"time": "get"}, "order": "get", "surface": {"detail": "post_get", "order": "post", "user": "post"}, "user": "get"}, "v2": {"country": "put", "list": "put"}, "v3": {"languages": "get", "surface": {"detail": "delete", "list": "delete"}, "user": "get"}}

這樣做的目的是方便下一步畫出樹,結構圖能夠清晰的比較差異。

本作品採用《CC 協議》,轉載必須註明作者和本文連結

相關文章