jpsider / RestPS

Simple ReST Framework for Powershell
MIT License
114 stars 31 forks source link

Begginer question #75

Closed rvencu closed 1 year ago

rvencu commented 1 year ago

Hi, I need to output some nested objects as a valid JSON. I have an AD attribute with multiple string values that I want to split into objects. This command:

Select-Object @{n='project';e={$_.Name}}, @{n='parent';e={$member}}, @{n='quota';e={$_.accountNameHistory -split(' ')}}

is rendering

    {
        "project":  "laion",
        "parent":  "root",
        "quota":  {
                      "value":  [
                                    "sagemaker2|0|0",
                                    "sagemaker||",
                                    "cw-prod|0|0"
                                ],
                      "Count":  3
                  }
    }

And I want to get something like this instead:

    {
        "project":  "laion",
        "parent":  "root",
        "quota":  {
                      "value":  [
                                    {"cluster":"sagemaker2", "gpus": 0, "budget": 0},
                                    {"cluster":"sagemaker", "gpus": null, "budget": null},
                                    {"cluster":"cw-prod", "gpus": 0, "budget": 0}
                                ],
                      "Count":  3
                  }
    }

I tried to build an object $quota and nest it into the output, but I always get an array of strings that still need to be converted into objects. $quota = $_.accountNameHistory -split(' ') | ForEach-Object {Write-Output $_; } | Select-Object @{n='cluster';e={$_.split("|")[0]}}, @{n='gpus';e={$_.split("|")[1]}}, @{n='budget';e={$_.split("|")[2]}} When I did this, the best I could obtain was still not what I expected:

    {
        "project":  "laion",
        "parent":  "root",
        "quota":  {
                      "value":  [
                                    "@{cluster=sagemaker2; gpus=0; budget=0}",
                                    "@{cluster=sagemaker; gpus=; budget=}",
                                    "@{cluster=cw-prod; gpus=0; budget=0}"
                                ],
                      "Count":  3
                  }
    }
rvencu commented 1 year ago

Found the problem, the ConvertTo-JSON command needs a -Depth 3 at minimum

rvencu commented 1 year ago

Fixed:

  1. I added "ResponseContentType" : "application/json" in the route definition
  2. I returned $Message | ConvertTo-Json -Depth 3 from the script where the message contains nested objects as described above
jpsider commented 1 year ago

Great work!