Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

batch file, read json file into string

Tags:

batch-file

I need to read a json file:

{
   "key": {
       "subkey": "value"
   }
}

so I can pass it as an argument to a command:

program -e SETTINGS=<JSON FILE AS STRING>
like image 378
Chris Avatar asked Feb 26 '26 18:02

Chris


1 Answers

Combining the answers to these questions...

  • How to read entire content of a text file in batch
  • Escape “double quotes” inside batch's input parameters

... we can write the following batch file:

:: Make it possible to read immediate value of variable using !variable! syntax.
setlocal enabledelayedexpansion

:: Read file "test.json" into variable data, removing line breaks.
set data=
for /f "delims=" %%x in (test.json) do set "data=!data!%%x"

:: Escape double quotes in data
set data=%data:"=\"%

:: Finally call program with the entire content of the JSON file as parameter
program -e "SETTINGS=%data%"

Note that when using the cmd.exe command processor, the maximum length for a commandline and also for environment variables is 8191 characters, so this will obviously restrict the maximum size of the JSON file you can pass.

like image 73
zett42 Avatar answered Mar 02 '26 08:03

zett42



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!