Home > front end >  creating json variable from txt file data in batch script
creating json variable from txt file data in batch script

Time:04-22

I have a txt file with input as -

First Line data here ...
Second, line data ; here
Third. line data here ..,

I have the following bat script code to read the txt file line by line and have value in tmp variable should ideally look like -

{ "s1":"First Line data here ...","s2":"Second, line data ; here","s3":"Third. line data here ..,"}

bat script code that is not giving me the expected output looks like -

@echo off
set /a count=1
set tmp=

SETLOCAL DisableDelayedExpansion
FOR /F "usebackq delims=" %%a in (`"findstr /n ^^ data.txt"`) do (
    set "var=%%a"
    SETLOCAL EnableDelayedExpansion
    set "var=!var:*:=!"
    echo(!var!
    call :processline !var!
    ENDLOCAL
)
pause
goto :END


:processline
set txt="%*"
set inp="s%count%"
IF "!tmp!" EQU "" (
        echo if called
        set tmp=%inp%:%txt%
    ) ELSE (
        echo else called
        set tmp=%tmp%,%inp%:%txt%
    )
set /a count =1
exit /b 0

:END
echo end called
echo -------
echo %tmp%}
pause

through some debugging i noticed that line "set tmp=%inp%:%txt%" is actually not getting set in global scope and always remaining empty, how can I modify this code to achieve the desired json looking output in tmp ?

CodePudding user response:

@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
rem The following settings for the source directory & filename are names
rem that I use for testing and deliberately include names which include spaces to make sure
rem that the process works using such names. These will need to be changed to suit your situation.

SET "sourcedir=u:\your files"
SET "filename1=%sourcedir%\q71959582.txt"
SET "json="

FOR /F "usebackq tokens=1*delims=:" %%b in (`findstr /n . "%filename1%"`) do SET "json=!json!"s%%b":"%%c","
SET "json={ %json:~0,-1%}"
SET json

The findstr simply prefixes each line of the file with serial:.

The for /f parses the resultant line, puts the serial number in %%b and the remainder of the line after the : in %%c.

The set simply appends "s<serialnumber>":"<line contents>", to the existing value of json

Then all that's required is to add the prefix and suffix braces to the built json value, all bar the terminal ,

The reason your code did not work (I didn't try it, so this is theory) is that the setlocal/endlocal bracket within the for loop establishes a local copy of the environment, manipulates it, and then restores the original values when the endlocal is executed.

Since you execute a setlocal enabledelayedexpansion at the start of the code, delayedexpansion is turned on, so you don't need to turn it on again. Your code may work without the disappearing modified values if you simply remove the setlocal and endlocal commands from within the for loop.

  • Related