我有一个文件路径列表作为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",
.....
.....
....
}
}
}
答案 0 :(得分:0)
您可以尝试这种方式,递归生成一个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"}