2013-04-13 24 views
0

我有一個文本文件與文件夾結構:Cmd的樹到JSON

+---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 

我使用tree接收到的命令從windows CMD。 我想知道是否有簡單的方法將此結構轉換爲json

對於這樣的事情來說,手動操作並不難,但我需要爲12TB文件夾執行此操作。

回答

5

好的,我對JSON並不是很熟悉。我看着this線程並寫了一個批處理腳本。請讓我知道,如果我可以改進。

@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 

用法:tree2json [startfolder] [>file.txt]

+0

漂亮!我所要做的就是將'''添加到所有名稱(IE'echo(%pre%type:「folder」,'='echo(%pre%「type」:「folder」,'),我需要用'/'運行''替換'''。非常感謝:D –

+0

「用'替換''''''' –

+0

嗨,但我的代碼中沒有」\「,你是什麼意思? – Endoro