จะแปลงพา ธ ของไฟล์เป็น treeview ได้อย่างไร?

ตอนนี้ฉันมีไฟล์บางไฟล์ใน python ที่มีรูปแบบพา ธ ของไฟล์ดังต่อไปนี้:

a/b/c/d/e/file1
a/b/c/d/e/file2
a/f/g/h/i/file3
a/f/g/h/i/file4

ตอนนี้ เมื่อฉันดึงข้อมูลเส้นทางเหล่านี้ใน Python ฉันต้องการเปลี่ยนสิ่งนี้เป็นรูปแบบ JSON ที่ปลั๊กอิน jquery บุคคลที่สาม (เช่น fancytree, jqxTree) สามารถอ่านได้เพื่อแปลงเป็น treeview อาจมีวิธีที่ง่ายกว่านี้อีก โปรดแนะนำ ขอบคุณ!


person return 0    schedule 05.08.2015    source แหล่งที่มา


คำตอบ (1)


จาก Python คุณสามารถสร้าง JSON ที่คุณต้องการได้ดังต่อไปนี้ (โปรดทราบว่าการเยื้องและการเรียงลำดับไม่จำเป็นหากคุณเพียงจัดส่ง JSON ข้ามบรรทัด แต่ทำให้เอาต์พุตสามารถอ่านได้สำหรับการดีบัก):

import collections
import json

myfiles = '''
    a/b/c/d/e/file1
    a/b/c/d/e/file2
    a/f/g/h/i/file3
    a/f/g/h/i/file4
'''

# Convert to a list
myfiles = myfiles.split()


def recursive_dict():
    """
    This function returns a defaultdict() object
    that will always return new defaultdict() objects
    as the values for any non-existent dict keys.
    Those new defaultdict() objects will likewise
    return new defaultdict() objects as the values
    for non-existent keys, ad infinitum.
    """
    return collections.defaultdict(recursive_dict)


def insert_file(mydict, fname):
    for part in fname.split('/'):
        mydict = mydict[part]

    # If you want to record that this was a terminal,
    # you can do something like this, too:
    # mydict[None] = True

topdict = recursive_dict()
for fname in myfiles:
    insert_file(topdict, fname)

print(json.dumps(topdict, sort_keys=True,
                indent=4, separators=(',', ': ')))

รหัสนี้สร้างผลลัพธ์ต่อไปนี้:

{
    "a": {
        "b": {
            "c": {
                "d": {
                    "e": {
                        "file1": {},
                        "file2": {}
                    }
                }
            }
        },
        "f": {
            "g": {
                "h": {
                    "i": {
                        "file3": {},
                        "file4": {}
                    }
                }
            }
        }
    }
}
person Patrick Maupin    schedule 06.08.2015
comment
def recursive_dict(): return collections.defaultdict(recursive_dict) ทำหน้าที่อะไร? - person return 0; 10.08.2015