使用python将文件路径的字符串解析为json

2024-10-02 04:34:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我有下面的路径字符串列表。如何将其转换为完整的json对象

foldersList = [
    '1/',
    '1/2/',
    '1/2/2.txt',
    '1/2/5/',
    '1/5.txt',
    '2/',
    '2/test.txt',
    'test.json'
]

如何将其转换为完整的json对象,如下所示

{
    "fileMenu":{
        "list":[
            {
                "fileType":"d",
                "name":"1",
                "subFolders":[
                    {
                        "fileType":"-",
                        "name":"5.txt",
                    },
                    {
                        "fileType":"d",
                        "name":"2",
                        "subFolders":[
                            {
                                "fileType":"-",
                                "name":"2.txt",
                            },
                            {
                                "date":1594983597000,
                                "fileType":"d",
                                "name":"5",
                                "size":0,
                                "subFolders":[]
                            }]
                    }]
            },
            {
                "fileType":"d",
                "name":"2",
                "subFolders":[{
                    "fileType":"-",
                    "name":"test.txt"
                }]
            },
            {
                "fileType":"-",
                "name":"test.json"
            }],
        "status":"OK"
    }
}

如何做到这一点?我尝试了一些代码片段

foldersList = [
    '1/',
    '1/2/',
    '1/2/2.txt',
    '1/2/5/',
    '1/5.txt',
    '2/',
    '2/test.txt',
    'test.json'
]

foldersJson = {}
nodeInfoList = []
nodeInfoDic = {}

for i, path in enumerate(foldersList):
    nodeInfoDic = foldersJson
    for j,node in enumerate(path.split('/')):
        if node != '':
            if nodeInfoDic.has_key(node) != True:
                nodeInfoDic[node] = {}
            nodeInfoDic = nodeInfoDic[node]
            # print(foldersJson)
    nodeInfoList.append(nodeInfoDic)
    print(nodeInfoList)

# print(foldersJson)

Tags: path对象nametesttxtnodejsonfor

热门问题