cloudbase / powershell-yaml

PowerShell CmdLets for YAML format manipulation
Apache License 2.0
434 stars 78 forks source link

Yaml output is not respected when exporting Powershell nested classes. #118

Closed Stephanevg closed 3 months ago

Stephanevg commented 11 months ago

Hi, I do have the following issue.

Class WoopCol {
  [woop[]]$Woops

  add([woop]$woop){
    $this.Woops += $woop
  }
}
Class woop {
  [String]$Name = "woop"
  [String]$Status = "running"
}

$col = [woopCol]::New()
$woop = [woop]::New()
$wap = [woop]::New()
$wap.Name = "wap"

$col.add($woop)
$col.add($wap)

$col | ConvertTo-Yaml

the result I get is the following:

Woops:
  - Name: woop
    Status: running
  - Name: wap
    Status: running

What I am actually expecting is:

woop: running
wap: running

Would this be the same root issue as #106 ?

gabriel-samfira commented 3 months ago

Hi @Stephanevg

I don't think it's the same case. You're defining a class woop which has 2 attributes (Name and Status). You then have another class called WoopCol which has a Woops attribute which is an array.

The serializer looks at the attributes of a class and serializes them. The ConvertTo-Json commandlet seems to do the same thing:

PS /home/gabriel> Class woop {       
>>   [String]$Name = "woop"
>>   [String]$Status = "running"
>> }
PS /home/gabriel> 
PS /home/gabriel> Class WoopCol {
>>   [woop[]]$Woops
>> 
>>   add([woop]$woop){
>>     $this.Woops += $woop
>>   }
>> }
PS /home/gabriel> 
PS /home/gabriel> $col = [woopCol]::New()
PS /home/gabriel> $woop = [woop]::New()
PS /home/gabriel> $wap = [woop]::New()
PS /home/gabriel> $wap.Name = "wap"
PS /home/gabriel> 
PS /home/gabriel> $col.add($woop)
PS /home/gabriel> $col.add($wap) 
PS /home/gabriel> ConvertTo-Json $col
{
  "Woops": [
    {
      "Name": "woop",
      "Status": "running"
    },
    {
      "Name": "wap",
      "Status": "running"
    }
  ]
}

The expected output you mentioned is a hashtable, whereas $col.Woops is an array. This sounds like a case for a Serialize() method in your class that creates the desired structure from the properties of the class, before sending them to ConvertTo-Yaml or ConvertTo-Json.