This is my JSON I want to set only "1.1.3" which is version from "stable" object to a variable(without quotes) in a batch file. I want it dynamic, maybe in future composer changed it into "version": "1.1.3.6" or even "version": "1.1.3-beta2", I want get whatever value of version.
Thank you.
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}]
}
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%
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%
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);