简体   繁体   English

在python中将路径转换为json格式

[英]convert path to json format in python

I have a file path lists as a txt file and needs to convert into json format. 我有一个文件路径列表作为txt文件,需要转换为json格式。 for example, 例如,

/src/test/org/apache/hadoop/ipc/TestRPC.java
/src/test/org/apache/hadoop/ipc/TestRPC2.java

I tried : 我试过了 :

for item in input:
    hierarchy = item.split('/')
    hierarchy = hierarchy[1:]
    local_result = result
    children=[]
    for node in hierarchy:
        print node
        if node in local_result: 
            local_result[node]
            local_result[node] = children
print result

but it has different result than what i want. 但结果却与我想要的不同。

in this case, i wanna make json file like below. 在这种情况下,我想制作如下的json文件。

{
    "name": "src",
    "children": {
        "name": "test",
        "children": {
            "name": "org",
.....
.....
....

        }
    }
}

You can try this way, recursively generate a dict and convert it to json: 您可以尝试这种方式,以递归方式生成字典并将其转换为json:

import json

file_path="/src/test/org/apache/hadoop/ipc/TestRPC.java"
l=file_path.split('/')[1:]

def gen_json(l,d=dict()):
    tmp = {}
    if not d:
        d["name"] = l.pop(-1)
    tmp["children"]=d
    tmp["name"]=l.pop(-1)
    return gen_json(l,tmp) if l else tmp

print(json.dumps(gen_json(l), ensure_ascii=False))

Output: 输出:

{"children": {"children": {"children": {"children": {"children": {"children": {"name": "TestRPC.java"}, "name": "ipc"}, "name": "hadoop"}, "name": "apache"}, "name": "org"}, "name": "test"}, "name": "src"}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM