将json配置值获取到windows脚本变量中

时间:2015-09-15 11:32:28

标签: json windows batch-file cmd jq

我想解析config.json文件并将一些特定值转换为变量。

以下命令正在运行,它从json打印值: type config.json | "jq-win64.exe" .path.editor

问题是如何将这个值变成某个变量?

我试过这个,但是没有用: set editorPath = type config.json | "jq-win64.exe" -r .path.editor

结果是%editorPath%为空

也许它与jq库(https://stedolan.github.io/jq/)有关,但我在Windows shell中非常棒,所以也许有人可以帮助解决这个问题。

由于

3 个答案:

答案 0 :(得分:2)

通常,当您想要将命令的输出捕获到变量时,请使用for /F循环。 for /f "delims=" %%I in ('command') do set "variable=%%I"或类似的。有关详细信息,请参阅cmd控制台中的help for

可以使JScript解释JSON类似于JavaScript的方式。有security concerns;但如果您可以合理地确定没有人可能将恶意代码插入JSON,您可以解析它而无需第三方工具。

此示例脚本结合了上面提到的两个想法 - 使用cscript.exe调用JScript代码块,并使用for /f循环捕获其输出。

<强> 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);

<强>输出:

  

编辑:......价值......

答案 1 :(得分:0)

以下是使用jq的两种方法的说明:

@echo off
setlocal

for /f "delims=" %%I in ('jq -n -r "\"123\""') do set A=%%I
echo A is %A%

jq -n -r  "@sh \"set B=123\"" > setvars.bat
call .\setvars.bat
echo B is %B%

在第一个示例中,批处理文件确定变量名称;在第二个例子中,jq程序确定变量名称。

顺便说一下,对于非Windows用户,jq Cookbook中有一个“配方”。

答案 2 :(得分:0)

对于Xidel,这非常简单。

点符号:

xidel -s config.json -e "($json).path.editor"

XPath表示法:

xidel -s config.json -e "$json/path/editor"

or even shorter

xidel -s config.json -e "$json//editor"

将值导出到“ editorPath”变量:

FOR /F "delims=" %A IN ('xidel -s config.json -e "editorPath:=$json//editor" --output-format^=cmd') DO %A