批处理文件解析JSON

P9Q*_*P9Q 0 json batch-file

这是我的JSON,我只想将批处理文件中的“稳定”对象的版本设置为“ 1.1.3”(不带引号)。我希望它是动态的,也许在将来的作曲家将其更改为“版本”:“ 1.1.3.6”,甚至是“版本”:“ 1.1.3-beta2”,我都希望获得任何版本的值。

谢谢。

myFile.json

{
    "stable": [{"path": "/download/1.1.3/composer.phar", "version": "1.1.3", "min-php": 50300}],
    "preview": [{"path": "/download/1.1.3/composer.phar", "version": "1.1.3", "min-php": 50300}],
    "snapshot": [{"path": "/composer.phar", "version": "334d0cce6b056e7555daf4c68c48cbe40ee4d51a", "min-php": 50300}]
}
Run Code Online (Sandbox Code Playgroud)

roj*_*ojo 5

For the love of Pete! Use a JSON parser. The data is already hierarchical. It's more graceful to objectify it and dig down the hierarchy than to tokenize it and count the lines / words.

@echo off & setlocal

set "jsonfile=test.json"

set "psCmd="add-type -As System.Web.Extensions;^
$JSON = new-object Web.Script.Serialization.JavaScriptSerializer;^
$JSON.DeserializeObject($input).stable.version""

for /f %%I in ('^<"%jsonfile%" powershell -noprofile %psCmd%') do set "version=%%I"

echo Version: %version%
Run Code Online (Sandbox Code Playgroud)

As an added bonus, if you're calling a PowerShell snippet anyway, you can also use Invoke-WebRequest to fetch the JSON from the web.

@echo off & setlocal

set "jsonURL=https://getcomposer.org/versions"

set "psCmd="add-type -As System.Web.Extensions;^
$JSON = new-object Web.Script.Serialization.JavaScriptSerializer;^
$JSON.DeserializeObject((Invoke-WebRequest %jsonURL%).content).stable.version""

for /f %%I in ('powershell -noprofile %psCmd%') do set "version=%%I"

echo Version: %version%
Run Code Online (Sandbox Code Playgroud)

If you need compatibility with XP / Vista or if you just want a script that runs faster than the PowerShell helper, you can use JScript to achieve the same effect.

@if (@CodeSection == @Batch) @then
@echo off & setlocal

set "URL=https://getcomposer.org/versions"

for /f "delims=" %%I in ('cscript /nologo /e:JScript "%~f0" "%URL%"') do set "ver=%%I"

echo Version: %ver%

goto :EOF
@end // end Batch / begin JScript hybrid code

var htmlfile = WSH.CreateObject('htmlfile'),
    x = WSH.CreateObject("Microsoft.XMLHTTP");

x.open("GET",WSH.Arguments(0),true);
x.setRequestHeader('User-Agent','XMLHTTP/1.0');
x.send('');
while (x.readyState != 4) WSH.Sleep(50);

htmlfile.write('<meta http-equiv="x-ua-compatible" content="IE=9" />');
var obj = htmlfile.parentWindow.JSON.parse(x.responseText);
htmlfile.close();

WSH.Echo(obj.stable[0].version);
Run Code Online (Sandbox Code Playgroud)