0

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",
.....
.....
....

        }
    }
}
1
  • 1
    You might want to checkout stackoverflow.com/questions/8484943/…, while the end result isn't a json, a tree and a nested json object aren't that different. Perhaps you can reuse the logic. Commented Apr 8, 2017 at 2:33

1 Answer 1

1

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"}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.