【问题标题】:Get json config value into windows script variable将 json 配置值获取到 windows 脚本变量中
【发布时间】:2015-09-15 11:32:27
【问题描述】:

我想解析 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 中很菜鸟,所以也许有人可以帮助解决这个问题。

谢谢

【问题讨论】:

  • 您可能会发现this answer 很有用。由于您的 JSON 格式正确,请从 eval 行和 echo editor: !editor! 中删除大括号
  • 一般来说,当您想将命令的输出捕获到变量时,请使用for /F 循环。 for /f "delims=" %%I in ('command') do set "variable=%%I" 或类似的。有关更多信息,请在 cmd 控制台中查看 help for。
  • 如果以下答案之一有帮助,请考虑选择一个标记为已接受。 See this page 解释为什么这很重要。

标签: json windows batch-file cmd jq


【解决方案1】:

一般来说,当您想将命令的输出捕获到变量时,请使用for /F 循环。 for /f "delims=" %%I in ('command') do set "variable=%%I" 或类似的。请在 cmd 控制台中查看 help for 了解更多信息。


可以让 JScript 以类似于 JavaScript 的方式解释 JSON。有security concerns;但如果您可以合理地确定没有人可能将恶意代码插入 JSON,您可以在不需要 3rd 方工具的情况下对其进行解析。


这个示例脚本结合了上面提到的两个想法 - 使用 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);

输出:

编辑:...值...

【讨论】:

  • 谢谢,这帮助我完全理解了问题。现在我有类似的东西:for /f "delims=" %%I in ('readConfig .path.to.something') do set PathToSomething=%%I,它似乎正在做我需要的事情。 readConfig 只是输出 jq 命令...
【解决方案2】:

以下是使用 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 中有一个关于此的“秘诀”。

【讨论】:

    【解决方案3】:

    这对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
    

    【讨论】:

      猜你喜欢
      • 2016-04-12
      • 1970-01-01
      • 1970-01-01
      • 2013-06-15
      • 1970-01-01
      • 2015-10-09
      • 2020-05-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多