Skip to content

Instantly share code, notes, and snippets.

@juliostanley
Last active November 27, 2019 02:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save juliostanley/08eae4e906d37f11e0bf73af1e84a4a7 to your computer and use it in GitHub Desktop.
Save juliostanley/08eae4e906d37f11e0bf73af1e84a4a7 to your computer and use it in GitHub Desktop.
PowerShell JSON and YAML
#!/usr/bin/env pwsh
# NOTE: Strips out false and null.
(gc file1.json -raw) | jq '[paths(scalars) as $path | { ($path | map(tostring) | join(\".\")): getpath($path) } ] | add'
#!/usr/bin/env pwsh
@((gc file1.json -raw),(gc file2.json -raw)) | jq -s '.[0] * .[1]'
#!/usr/bin/env pwsh
# NOTE: Interpolates ${some.path} with the value found at that path. Alternative method handles json values except for null
Function Get-ObjPath($obj, $objPath ) {
$pathParts = $objPath.split(".");
$output = $obj;
foreach ( $nested in $pathParts ) {
$output = $output.$nested;
if(!$output) { return $output; }
}
return $output;
}
$merged = @((gc file1.json -raw),(gc file2.json -raw)) | jq -s '.[0] * .[1]'
$merged
$mergedObj = $merged | ConvertFrom-Json
$filled = [regex]::Replace(($merged),"\$\{([^}]+)?\}",{param($match) "$(Get-ObjPath $mergedObj $match.Groups[1].Value)"})
# $filled = [regex]::Replace(($merged),"`"\$\{([^}]+)?\}`"",{param($match) "$(Get-ObjPath $mergedObj $match.Groups[1].Value | ConvertTo-Json)"})
$filled | ConvertFrom-Json | ConvertTo-Json -Depth 10 # -Compress
#!/usr/bin/env pwsh
if (!(Get-Module -ListAvailable -Name powershell-yaml)) { Install-Module -Scope CurrentUser -Name powershell-yaml -RequiredVersion 0.4.0 -Confirm:$False -Force }
if (!(Get-Module -ListAvailable -Name powershell-yaml)) { exit }
$yaml = (gc file1.yaml) | Out-String | ConvertFrom-Yaml
$json = $yaml | ConvertTo-Json -Depth 10
# Use jq on object if needed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment