Sam
Sam

Reputation: 43

JQ with Windows Batch - select failing

Using a Windows batch file with JQ and trying to pipe the select filter.

Example Json which is being parsed with JQ:

{
  "name": "test-mmc-deploy",
  "id": "local$3d2075c5-73c0-47aa-8df5-cee3a70f68c4",
  "lastModified": "Mon, 1 May 2017 13:56:15.980 AEST",
  "servers": [
    "local$520ee705-bdbb-4132-94cf-63bb213d2b46"
  ],
  "status": "DEPLOYED",
  "applications": [
    "local$f3d791bd-14d9-4491-9541-5fa04d8c3164"
  ],
  "href": "http://localhost:9090/mmc-console-3.8.2/api/deployments/local$3d2075c5-73c0-47aa-8df5-cee3a70f68c4",
  "clusterNames": [],
  "reconciled": false,
  "clusterIds": []
}

Normal command line JQ works with Curl and gives output as follows:

curl --basic -u admin:admin http://localhost:9090/mmc-console-3.8.2/api/deployments | jq ".data[] | select(.name==\"test-mmc-deploy\").id

"local$3d2075c5-73c0-47aa-8df5-cee3a70f68c4"

Trying to get the below command working in a Windows batch file is creating an escape character nightmare. Need some help please.

for /f "tokens=*" %%a in ('echo %%app_deploy_list%% ^| jq "".data[] ^| select(.name==\"test-mmc-deploy\"^).id""') do (set app_id=%%a)
echo Application found: %app_id%

where %%app_deploy_list%% holds the json declared above.

The error I am getting is: 'select' is not recognized as an internal or external command

Upvotes: 4

Views: 7343

Answers (2)

Jeff Mercado
Jeff Mercado

Reputation: 134521

You're escaping things unnecessarily, the command interpreter is probably inserting them literally. That and your use of double quotes is inconsistent. You probably cut the strings off prematurely and the filter is effectively being run as additional piped commands.

Running this directly in a command prompt works for me:

for /f "tokens=*" %a in ('jq ".data[] | select(.name==\"test-mmc-deploy\").id" input.json') do (echo "Application found: %a")

Then in a batch file, you only need to double the % for your loop variable.

for /f "tokens=*" %%a in ('jq ".data[] | select(.name==\"test-mmc-deploy\").id" input.json') do (
    set app_id=%%a
)
echo Application found: %app_id%

To be able to pipe the curl response directly to jq, just escape the pipe (and nothing else).

for /f "tokens=*" %%a in ('curl --basic -u admin:admin http://localhost:9090/mmc-console-3.8.2/api/deployments ^| jq ".data[] | select(.name==\"test-mmc-deploy\").id"') do (
    set app_id=%%a
)
echo Application found: %app_id%

Upvotes: 2

Magoo
Magoo

Reputation: 80138

Windows is attempting to pipe the output of jq into select, but can't find the executable select.

I'm unfamiliar with curl and jq but it would appear that you require a literal |. In the quoted-command format you are using, a literal | can be produced with ^^^|

Upvotes: 1

Related Questions