Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在python中将路径转换为json格式_Python_Json_Path_Format - Fatal编程技术网

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

在python中将路径转换为json格式,python,json,path,format,Python,Json,Path,Format,我有一个文件路径列表作为txt文件,需要转换成json格式。 比如说, /src/test/org/apache/hadoop/ipc/TestRPC.java /src/test/org/apache/hadoop/ipc/TestRPC2.java 我试过: for item in input: hierarchy = item.split('/') hierarchy = hierarchy[1:] local_result = result childr

我有一个文件路径列表作为txt文件,需要转换成json格式。 比如说,

/src/test/org/apache/hadoop/ipc/TestRPC.java
/src/test/org/apache/hadoop/ipc/TestRPC2.java
我试过:

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
但结果和我想要的不同

在这种情况下,我想制作json文件,如下所示

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

        }
    }
}

您可以尝试这种方式,递归生成dict并将其转换为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))
输出:

{"children": {"children": {"children": {"children": {"children": {"children": {"name": "TestRPC.java"}, "name": "ipc"}, "name": "hadoop"}, "name": "apache"}, "name": "org"}, "name": "test"}, "name": "src"}
您可能希望签出,虽然最终结果不是json,但树和嵌套的json对象并没有什么不同。也许你可以重用这个逻辑。