Batch to convert txt file into json file

Posted on

QUESTION :

I have a text file named, proxy.txt

which contains,

84.15.160.174:4145
178.208.17.195:9999
58.253.154.117:9999
112.87.71.194:9999

I found this URL ยป https://shancarter.github.io/mr-data-converter/
converts the text into json.

Same i like to have in a batch..

expected output in output.txt

[{"84.15.160.174:4145":"178.208.17.195:9999"},
{"58.253.154.117:9999":"112.87.71.194:9999"}]

ANSWER :

[test.bat]

@echo off 
SetLocal EnableDelayedExpansion
cls
set tmp=
echo [
FOR /F "tokens=1" %%a in (proxy.txt) do (
    IF "!tmp!"=="" (
        SET tmp=%%a
    ) ELSE (
        echo {"!tmp!":"%%a"},
        set tmp=
    )
)
echo {"%tmp%":""}]

[proxy.txt]

84.15.160.174:4145
178.208.17.195:9999
58.253.154.117:9999
112.87.71.194:9999

Output:

[
{"84.15.160.174:4145":"178.208.17.195:9999"},
{"58.253.154.117:9999":"112.87.71.194:9999"},
{"":""}]

[proxy.txt]

84.15.160.174:4145
178.208.17.195:9999
58.253.154.117:9999
112.87.71.194:9999
11.22.33.44:5555

Output:

[
{"84.15.160.174:4145":"178.208.17.195:9999"},
{"58.253.154.117:9999":"112.87.71.194:9999"},
{"11.22.33.44:5555":""}]

PS. If empty object is not safe for you (when the amount of lines is even) then you may add proper IF to the last echo. You may also wrap the FOR body into IF which will skip empty lines in proxy.txt if needed.

Leave a Reply

Your email address will not be published. Required fields are marked *