Building json from folder structure and vice versa
I'm trying to generate a json representation from a folder structure.
Examplee folder/file structure:
folder
|_ meta.xml
|_ subdir1
|_ textfile1.txt
|_ subdir2
|_ textfile2.txt
Manually generate the json representation of this structure:
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")
}
}
generates:
{
"dir":{
"file":{
"name":"meta.xml"
},
"folder":[
{
"name":"subdir1"
},
{
"file":[
{
"name":"textfile.txt"
}
]
},
[
{
"name":"subdir2"
},
{
"file":[
{
"name":"textfile3.txt"
}
]
}
]
]
}
}
Groovy way of walking the folder structure:
new File("./dir"开发者_StackOverflow ).eachFileRecurse{file ->
println file
}
generates:
.\dir\meta.xml
.\dir\subdir1
.\dir\subdir1\textfile1.txt
.\dir\subdir2
.\dir\subdir2\textfile2.txt
But how to put these together to generate this automatically?
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)
}
}
So the last thing left to do is convert paths
to JSON.
Hope it helps!
精彩评论