hunterex
hunterex

Reputation: 595

Why jq does not compile when I pass a Powershell variable?

Inspired by the solution here, I want to delete any JSON entry from components.schemas if it is not found in the $paths

Here is my Powershell script with jq:

$paths = jq '.. |.\"$ref\"? | select(. != null)' $srcJson
jq '.components.schemas |= with_entries( select( .key as $key | any(${paths}[]; index($key) )))' $srcJson | Out-File $destinationJson -Encoding UTF8

This is a sample JSON file before changes: https://codebeautify.org/online-json-editor/cbc78213

Then this is the expect JSON file after I run the Powershell script above: https://codebeautify.org/online-json-editor/cb8c4b2b

Notice that the BadSchemas is removed from the components.schemas

When I run the code in PowerShell, I got error message below:

jq: error: syntax error, unexpected '{', expecting IDENT or loc (Windows cmd shell quoting issues?) at , line 1: .components.schemas |= with_entries( select( .key as $key | any(${paths}[]; index($key) )))

Could anyone show me where have I done wrong?

Thanks

Upvotes: 1

Views: 873

Answers (2)

myBasementCloud
myBasementCloud

Reputation: 1

Have you tried breaking the strings passed to jq where you are passing an OS variable? I've had to use this on bash for Linux to deal with complex operations.

$paths = jq '.. |.\"'$ref'\"? | select(. != null)' $srcJson
jq '.components.schemas |= with_entries( select( .key as $key | any('${paths}'[]; index($key) )))' $srcJson | Out-File $destinationJson -Encoding UTF8

I can't test this, since I don't have your variables to work with, but that should allow the command interpreter to expand the powershell variables that you pass.

Feedback on this assumption for PowerShell would be good, since I'm trying to learn PowerShell but have been coding bash or Windows CMD so far, so not sure if this approach is a good resolution.

Upvotes: 0

Weeble
Weeble

Reputation: 17940

Powershell doesn't expand variables inside single quoted strings. If you want ${paths} to be expanded by Powershell it will need to be in double quotes.

However, in general this isn't the best way to pass variables to jq. It's better to use --arg and --argjson which respectively pass strings and json values in as jq variables.

I don't have a Windows machine to test this, but you should be able to do something like this:

$paths = jq '.. |.\"$ref\"? | select(. != null)' $srcJson | ConvertTo-Json
jq --argjson paths "$paths" '.components.schemas |= with_entries( select( .key as $key | any($paths[]; index($key) )))' $srcJson | Out-File $destinationJson -Encoding UTF8

Upvotes: 4

Related Questions