Windows – Batch file to read a file and create a JSON

batchbatch filewindows

I have a text file with some dozens of entries in the following format:

code: SETX
id: 1
msg: Message for setx

code: SETY
id: 2
msg: Message for sety
msg_ja: Japanese message for sety

As you can see, some entries might have keys that are not present in others (eg: msg_ja is in second entry, but not in the first).

What I need now is to read this text file and create a JSON from it. Eg:

global_var.SETX = {
  id: 1,
  msg: "Message for setx"
};

global_var.SETY = {
  id: 2,
  msg: "Message for sety",
  msg_ja: "Japanese message for sety"
};

How can I do this using a batch file?

Best Answer

Here's a start. There's just one slight issue: the last item in the JSON block still ends with a comma, but this code snippet will get you going.

@echo off
Setlocal EnableDelayedExpansion

set first=1

for /f "tokens=1,2" %%i in (input.txt) do (    
    if "%%i"=="code:" (
        if !first! neq 1 (
            echo }
        )               
        echo global_var.%%j = {
    ) else (
        echo   %%i %%j,
    )
    set first=0
)
echo }
Related Question