user2754162
user2754162

Reputation: 1

convert path to json format in python

I have a file path lists as a txt file and needs to convert into json format. 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.

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

        }
    }
}

Upvotes: 0

Views: 2438

Answers (1)

McGrady
McGrady

Reputation: 11477

You can try this way, recursively generate a dict and convert it to 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"}

Upvotes: 1

Related Questions