2017-04-08 188 views
0

我有一个文件路径列表作为txt文件,需要转换成json格式。 例如,将路径转换为python中的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", 
..... 
..... 
.... 

     } 
    } 
} 
+0

您可能要结帐http://stackoverflow.com/questions/8484943/construct-a-tree-from-list-os-file-paths-python-performance-dependent,虽然最终结果不是JSON,但树和嵌套的JSON对象没有那么不同。也许你可以重用逻辑。 – reticentroot

回答

0

你可以试试这个方法,递归地生成一个字典,并将其转换成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"}