0

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?

1 Answer 1

1

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 }
2
  • Thanks! This is what I've been looking for. One question: If there are no quotes surrounding the right-hand-side values, how should I change this script? (it breaks at spaces)
    – thameera
    Aug 27, 2014 at 7:02
  • I believe "tokens=1*" will take care of that
    – Berend
    Aug 28, 2014 at 7:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.