您好,我是批处理文件中的新手。我尝试对我的bash脚本做一些类似的事情。所以这是我的问题:
我想从github存储库获取所有版本/标签,以生成php documentor sami的配置文件。但是如何批量将JSON写入变量以获取版本?在我的bash脚本中,我做了这个并且它工作得很好:
function jsonDecode() {
json=$1
key=$2
echo ${json} | jq -r ${key}
}
ghUser="MisterMarlu"
ghRepo="sentence"
json=$(curl "https://api.github.com/repos/${ghUser}/${ghRepo}/tags")
versions=$(echo "${json}" | jq -c ".[]")
for version in ${versions[@]}; do
versionNumber=$(jsonDecode ${version} ".name")
echo " ->add( '${versionNumber}', '${versionNumber}' )" >> ${config}
done
# Here comes alot of code below this for loop..
这将输出" v0.0.1"和" v0.0.2"。总线如何在批处理文件中执行此操作?
修改
这是JSON响应,我只需要"name"
作为数组:
[
{
"name": "v0.0.2",
"zipball_url": "https://api.github.com/repos/MisterMarlu/sentence/zipball/v0.0.2",
"tarball_url": "https://api.github.com/repos/MisterMarlu/sentence/tarball/v0.0.2",
"commit": {
"sha": "82c4b6d74cc16816104934114766f0328e77ee66",
"url": "https://api.github.com/repos/MisterMarlu/sentence/commits/82c4b6d74cc16816104934114766f0328e77ee66"
},
"node_id": "MDM6UmVmMTMzMDM1MDMxOnYwLjAuMg=="
},
{
"name": "v0.0.1",
"zipball_url": "https://api.github.com/repos/MisterMarlu/sentence/zipball/v0.0.1",
"tarball_url": "https://api.github.com/repos/MisterMarlu/sentence/tarball/v0.0.1",
"commit": {
"sha": "0cf1a83a51716da3f42915c9eab571166845bb0b",
"url": "https://api.github.com/repos/MisterMarlu/sentence/commits/0cf1a83a51716da3f42915c9eab571166845bb0b"
},
"node_id": "MDM6UmVmMTMzMDM1MDMxOnYwLjAuMQ=="
}
]
答案 0 :(得分:0)
for /f
findstr
:: Q:\Test\2018\06\12\SU_50811698.cmd
@Echo off & SetLocal EnableDelayedExpansion
Set "ghUser=MisterMarlu"
Set "ghRepo=sentence"
Set "Version="
For /f "tokens=1,2 delims=:, " %%U in ('
curl "https://api.github.com/repos/%ghUser%/%ghRepo%/tags" 2^>Nul ^| findstr /i "\"name\""
') do Set "Version=!Version!,%%~V"
If defined Version (set "Version=%Version:~1%") Else (Set "Version=n/a")
Set Version
示例输出:
> Q:\Test\2018\06\12\SU_50811698.cmd
Version=v0.0.2,v0.0.1
您知道批处理没有真正的数组吗?
PowerShell中的另一种选择:
$ghUser="MisterMarlu"
$ghRepo="sentence"
$URL = "https://api.github.com/repos/$ghUser/$ghRepo/tags"
$Json=(curl.exe $URL)|ConvertFrom-json
$Json | Select name
name
----
v0.0.2
v0.0.1
答案 1 :(得分:0)
有了Xidel,它很简单:
xidel -s "https://api.github.com/repos/MisterMarlu/sentence/tags" -e "join($json()/name,',')"
结果显示:v0.0.2,v0.0.1
。
要将其导出为$config
/ %config%
...
重击:
eval "$(xidel -s "https://api.github.com/repos/MisterMarlu/sentence/tags" -e '
config:=join(
$json()/name,
","
)' --output-format=bash
)"
批次:
FOR /F "delims=" %%A IN ('xidel.exe -s "https://api.github.com/repos/MisterMarlu/sentence/tags" -e ^"
config:^=join^(
$json^(^)/name^,
'^,'
^)^" --output-format^=cmd
') DO %%A
或...
FOR /F "delims=" %%A IN ('xidel.exe -s "https://api.github.com/repos/MisterMarlu/sentence/tags" -e "config:=join($json()/name,',')" --output-format=cmd') DO %%A