【问题标题】:convert path to json format in python在python中将路径转换为json格式
【发布时间】:2017-04-08 01:44:46
【问题描述】:

我有一个文件路径列表为 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",
.....
.....
....

        }
    }
}

【问题讨论】:

标签: python json path format


【解决方案1】:

你可以试试这种方式,递归生成一个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"}

【讨论】:

    猜你喜欢
    • 2019-04-06
    • 1970-01-01
    • 2023-03-23
    • 2013-07-05
    • 1970-01-01
    • 2023-03-10
    • 2022-01-04
    • 2018-03-06
    • 2019-08-15
    相关资源
    最近更新 更多