2

I have a text file with a folder structure:

+---A Momentary Lapse of Reason
+---A Saucerful of Secrets
+---Animals
+---Atom Heart Mother
+---Delicate Sound Of Thunder
+---Echoes- The Best of Pink Floyd
|   +---Echoes- The Best of Pink Floyd Disc 1
|   \---Echoes- The Best of Pink Floyd Disc 2
+---Is There Anybody out There- The Wall- Live 1980-1981 Disc 1
+---Is There Anybody out There- The Wall- Live 1980-1981 Disc 2
\---Works

I received it from windows CMD using the tree command. I wanted to know if there is a simple way to convert this structure into json?

For something like this it isn't too hard to do it manually, but I need to do it for a 12TB folder.

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Dvir Levy
  • 8,018
  • 11
  • 39
  • 60

1 Answers1

6

OK, I'm not so familiar with JSON. I looked at this thread and wrote a batch script. Please let me know, if I can something improve.

@echo off &setlocal
if "%~1"=="" (set "root=.") else set "root=%~1"
set "pre0=                                    "

pushd %root%
echo(data = [
call:dirtree "%CD%" "1" "1"
popd
echo(];
goto:eof

:dirtree
setlocal
call set "pre=%%pre0:~-%~2%%
set /a ccount=%~3
set /a tcount=%~2+2
set /a dcount=0
for /d %%i in (*) do set /a dcount+=1
echo( %pre%{
echo(  %pre%"type": "folder",
echo(  %pre%"name": "%~nx1",
set "fpath=%~f1"
set "fpath=%fpath:\=/%"
echo(  %pre%"path": "%fpath%",
echo(  %pre%"childno": %ccount%,
if %dcount% equ 0 echo(  %pre%"subchilds": %dcount%
if %dcount% gtr 0 (
    echo(  %pre%"subchilds": %dcount%,
    echo(  %pre%"children": [
    for /d %%i in (*) do (
        for /f %%j in ('call echo "%%dcount%%"') do (
            cd "%%i"
            call:dirtree "%%i" "%tcount%" "%%j"
            cd ..
        )
        set /a dcount-=1
    )
    echo(  %pre%]
)
if %ccount% equ 1 (echo  %pre%}) else echo( %pre%},
endlocal
goto:eof

Usage: tree2json [startfolder] [>file.txt]

Community
  • 1
  • 1
Endoro
  • 37,015
  • 8
  • 50
  • 63
  • BEAUTIFUL! All I had to do is add `"` to all of the names (IE `echo( %pre%type: "folder",` = `echo( %pre%"type": "folder",`) and I need to run a "replace `\` with `/`. Thank you so much :D – Dvir Levy Apr 18 '13 at 12:21
  • "replace" `\ ` with `/` ** – Dvir Levy Apr 18 '13 at 13:33
  • When you do `"%~f1"` it gives the path to the folder. The path has `\ `'s and apparently `Json` doesn't like it. :P – Dvir Levy Apr 18 '13 at 14:53
  • 1
    OK, I can change this and add the missing double quotes (need some time, I'm on the tablet now) .... :) – Endoro Apr 18 '13 at 14:57