Above is variables.stg.yml
I am trying to read it in my Powershell code. I used
CodePudding user response:
The immediate problem with your code is that you're referencing $JsonParameter.parameters
when you really want $JsonParameters.variables
- the property name in the yaml file is variables
, not parameters
.
A less cumbersome way to obtain an object with the ABC
and Test
entries from the yaml file as properties would be to simply cast the hashtable generated by ConvertTo-Yaml
to a [PSCustomObject]
:
$documentWithVariables = Get-Content -Path ..\variables.stg.yml -Raw |ConvertFrom-Yaml
$oData = [PSCustomObject]$documentWithVariables.variables
Much simpler :)
CodePudding user response:
It seems like you're trying to use Convertto-YAML to converted to serialized JSON.
Accordding to their documentation you need to use the jsoncompatible
flag to do this.
Converting from YAML to JSON
The awesome YamlDotNet assembly allows us to serialize an object in a JSON compatible way. Unfortunately it does not support indentation. Here is a simple example:
Import-Module powershell-yaml
PS C:\> $yaml = @"
anArray:
- 1
- 2
- 3
nested:
array:
- this
- is
- an
- array
hello: world
"@
PS C:\> $obj = ConvertFrom-Yaml $yaml
PS C:\> $obj
Name Value
---- -----
anArray {1, 2, 3}
nested {array}
hello world
PS C:\> ConvertTo-Yaml -JsonCompatible $obj
{"anArray": [1, 2, 3], "nested": {"array": ["this", "is", "an", "array"]}, "hello": "world"}
# Or you could do it in one line.
PS C:\> ConvertFrom-Yaml $yaml | ConvertTo-Yaml -JsonCompatible
{"anArray": [1, 2, 3], "nested": {"array": ["this", "is", "an", "array"]}, "hello": "world"}
Your array is also not formatted correctly to be imported as a nested. Below is correct syntax:
variables:
ABC:
XYz
Test:
preprod01
Finally:
[pscustomobject]$os_list = (ConvertFrom-Yaml -yaml (get-content -Raw C:\Powershell\TestCSVs\variables.stg.yml))
[pscustomobject]$os_list = ConvertTo-Yaml $os_list -JsonCompatible
$os_list
$oData = $os_list.variables
$oData
PS:> {"variables": {"ABC": "XYz", "Test": "preprod01"}}