Search code examples
jsonwindowsbashbatch-file

How to get JSON from cURL as array in a batch file


Hi I'm very new in batch files. I try to do something simular to my bash script. So here is my problem:

I want to get all versions/tags from a github repository to generate a configuration file for the php documentor sami. But how can I write the JSON into a variable in batch to get the versions? In my bash script I did this and it's working fine:

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..

This will output "v0.0.1" and "v0.0.2". Bus how can I do this in a batch file?

EDIT
Here is the JSON response where I need just the "name" as array:

[
  {
    "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=="
  }
]

Solution

    • To process the output of another program you need a for /f
    • parsing the lines filtered by 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
    

    Sample output:

    > Q:\Test\2018\06\12\SU_50811698.cmd
    Version=v0.0.2,v0.0.1
    

    You are aware that batch has no real arrays?

    Just an alternative in 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