将目录结构转换为json?

时间:2016-10-17 14:15:59

标签: python json

我想转换一个项目层次结构,其中包含JSON字典中每个类或包的一些属性。例如

我正在使用python。谁能请给我一些基本的轮廓。我怎么能实现这一点。谢谢。因此我想要类似的东西:

a = package, a.b = package, a.b.c = class, a.b.d = class

j_string = {
    "my_data": {
        "a": "info": {},
        "b": {
            "info": {},
            "c": {
                "info": {}
            },
            "d": {
                "info": {}
            }
        }
    }
}

1 个答案:

答案 0 :(得分:0)

尝试将pkgutil.walk_packagesimportlib.import_module结合使用。

def get_all_module_of_a_package(pkg_name):
    pkg = importlib.import_module(pkg_name)
    for importer, name, is_pkg in pkgutil.walk_packages(pkg.__path__, pkg.__name__ + '.'):
        if is_pkg:
            continue
        print name # I just print them, you can build a dict you desired
        # do some other things (if you want to get member of a module)
        # use inspect.getmembers



>>> get_all_module_of_a_package('json')
json.decoder
json.encoder
json.scanner
json.tests.test_check_circular
json.tests.test_decode
json.tests.test_default
json.tests.test_dump
json.tests.test_encode_basestring_ascii
json.tests.test_fail
json.tests.test_float
json.tests.test_indent
json.tests.test_pass1
json.tests.test_pass2
json.tests.test_pass3
json.tests.test_recursion
json.tests.test_scanstring
json.tests.test_separators
json.tests.test_speedups
json.tests.test_tool
json.tests.test_unicode
json.tool
相关问题