【问题标题】:Building json from folder structure and vice versa从文件夹结构构建 json,反之亦然
【发布时间】:2010-05-27 18:30:47
【问题描述】:

我正在尝试从文件夹结构生成 json 表示。

示例文件夹/文件结构:

folder
|_ meta.xml
|_ subdir1
   |_ textfile1.txt
|_ subdir2
   |_ textfile2.txt 

手动生成这个结构的json表示:

def builder = new net.sf.json.groovy.JsonGroovyBuilder()
def json = builder.dir {
    file(name: "meta.xml")
    folder(name: "subdir1") {
        file(name: "textfile.txt")
    }
    folder(name: "subdir2") {
        file(name: "textfile3.txt")
    }
}

生成:

{
   "dir":{
      "file":{
         "name":"meta.xml"
      },
      "folder":[
         {
            "name":"subdir1"
         },
         {
            "file":[
               {
                  "name":"textfile.txt"
               }
            ]
         },
         [
            {
               "name":"subdir2"
            },
            {
               "file":[
                  {
                     "name":"textfile3.txt"
                  }
               ]
            }
         ]
      ]
   }
}

走文件夹结构的Groovy方式:

new File("./dir" ).eachFileRecurse{file ->
    println file
}

生成:

.\dir\meta.xml
.\dir\subdir1
.\dir\subdir1\textfile1.txt
.\dir\subdir2
.\dir\subdir2\textfile2.txt

但是如何将这些放在一起自动生成呢?

【问题讨论】:

    标签: json groovy structure directory


    【解决方案1】:
    def paths = [:]
    def listOfPaths = []
    
    def access = {d, path ->
        if (d[path] == null) {
            d[path] = [:]
        } 
        return d[path]        
    }
    
    new File('./dir').eachFileRecurse{ file ->
        listOfPaths << file.toString().tokenize('/')
    }
    
    listOfPaths.each{ path ->
        def currentPath = paths
        path.each { step ->
            currentPath = access(currentPath, step)
        }
    }
    

    所以最后要做的就是将paths 转换为 JSON。

    希望对你有帮助!

    【讨论】:

      猜你喜欢
      • 2018-05-01
      • 2014-01-04
      • 2022-10-24
      • 2011-03-22
      • 1970-01-01
      • 1970-01-01
      • 2020-04-08
      • 1970-01-01
      • 2017-07-05
      相关资源
      最近更新 更多