In general, when you want to capture the output of a command to a variable, use a for /F
loop. for /f "delims=" %%I in ('command') do set "variable=%%I"
or similar. See help for
in a cmd console for more info.
It is possible to make JScript interpret JSON similar to the way JavaScript would. There are security concerns; but if you can be reasonably certain no one is likely to insert malicious code into the JSON, you can parse it without requiring 3rd party tools.
This example script combines the two ideas mentioned above -- invoking a JScript code block with cscript.exe
, and capturing its output with a for /f
loop.
config.json:
{ "path" : { "editor" : "...value..." } }
parseJSON.bat:
@if (@CodeSection == @Batch) @then
@echo off
setlocal
set "JSONfile=config.json"
for /f "delims=" %%I in ('cscript /nologo /e:JScript "%~f0" "%JSONfile%"') do set "%%~I"
rem // Delayed expansion prevents path names with symbols (& or %) from choking the script
setlocal enabledelayedexpansion
echo editor: !editor!
endlocal
goto :EOF
@end // end batch / begin JScript chimera
var fso = WSH.CreateObject('scripting.filesystemobject'),
JSONfile = fso.OpenTextFile(WSH.Arguments(0), 1);
eval('obj = ' + JSONfile.ReadAll());
JSONfile.Close();
function walk(tree) {
for (var i in tree) {
if (typeof tree[i] === 'object') walk(tree[i]);
else WSH.Echo(i + '=' + tree[i]);
}
}
walk(obj);
Output:
editor: ...value...