Cmd tree to Json

2019-08-29 11:47发布

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.

1条回答
贪生不怕死
2楼-- · 2019-08-29 12:40

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]

查看更多
登录 后发表回答