首页 > 解决方案 > 使用 python 搜索 Json 目录

问题描述

我创建了一个包含特定目录的 Json 文件。我正在尝试编写一些允许用户进出每个“文件夹”的东西,几乎创建了一个命令行“文件资源管理器”

我的 json 文件格式如下:

{
    "children": [
        {
            "children": [
                {
                    "name": "somefile.cmd",
                    "path": "C:\\some\\directory\\somefile.cmd",
                    "type": "file"
                },
                {
                    "name": "otherfile.ps1",
                    "path": "C:\\some\\directory\\somefile.ps1",
                    "type": "file"
                },
                {
                    "name": "somefile.exe",
                    "path": "C:\\some\\directory\\somefile.exe",
                    "type": "file"
                }
            ],
            "name": "somefile",
            "path": "C:\\some\\directory",
            "type": "folder"
        },
        {
            "children": [
.
.
.

我正在使用的功能

def search_json(filename):
    json_file = open(filename)
    data = json.load(json_file)
    subsyst_count = 1
    subsyst_list = []
    #list of subsystems
    for i in data['children']:
        print(subsyst_count, i['name'])
        subsyst_list.append(i['name'])
        subsyst_count = subsyst_count + 1
    user = int(input('Which Subsystem?'))
    #search json for children of subsyst_list[user]
    print(subsyst_list[user])
    for i in data['children']:
        if i['name'] == subsyst_list[user]:
            print(i['name'])
            for j in i['name']:
                print(j[0])

我希望它进入第一个子文件夹,计算它下面的所有文件夹,并提示用户选择一个数字来确定要进入的子系统。然后我希望它搜索新的“子”子系统目录并再次编号要进入的文件或要选择的文件。相反,当我有

   print(j['name'])

然后当我有时,该函数只是拼写子系统的名称:

   print(j['0'])

标签: pythonjsondirectory

解决方案


推荐阅读