Home > Enterprise >  Unable to get array inside a array list in powershell to json
Unable to get array inside a array list in powershell to json

Time:10-21

I am trying to write a PowerShell script that will return me a JSON...This is what I have been able to get.

$stepBase = @{}
$wizardDataArray = @{}
$stepTypeData =@{}
$step = New-Object System.Collections.ArrayList

$wizardData = @{"mode"="Add"; "resourceName"="basicServer";
"serverName"="demoServer"; "serverAddress"="xyz.abc.info";
"activeDbCatalog"="demodb";}

$stepData = @{"wizardType"="baseServer"; "wizardData"=$wizardData}

$stepTypeData = @{"stepType"="runWizard"; "stepData"=$stepData}
$step.Add(@{"steps"=$stepTypeData})


$stepBase.Add("steps", $step)
$stepBase | ConvertTo-Json -Depth 10

This is the ouput :

0
{
  "steps": [
    {
      "steps": {
        "stepData": {
          "wizardType": "baseServer",
          "wizardData": {
            "serverAddress": "xyz.abc.info",
            "activeDbCatalog": "demodb",
            "resourceName": "basicServer",
            "mode": "Add",
            "serverName": "demoServer"
          }
        },
        "stepType": "runWizard"
      }
    }
  ]
}

But this is different from my need...which is this...

{
  "steps": [
    {
      "stepType": "runWizard",
      "stepData": {
        "wizardType": "baseServer",
        "wizardData": {
          "mode": "Add",
          "resourceName": "basicServer",
          "serverName": "demoServer",
          "serverAddress": "xyz.abc.info",
          "activeDbCatalog": "demoDb"
        }
      }
    }
  ]
}

I am not able to get my array inside the list without mentioning the key "step".

CodePudding user response:

Try this...

$stepBase = @{}
$step = New-Object System.Collections.ArrayList

$wizardData = @{"mode"="Add"; "resourceName"="basicServer";
"serverName"="demoServer"; "serverAddress"="xyz.abc.info";
"activeDbCatalog"="demodb";}

$stepData = @{"wizardType"="demoServer"; "wizardData"=$wizardData}

$step.Add(@{"stepType"="runWizard"; "stepData"=$stepData})
$stepBase.Add("steps", $step)
$stepBase | ConvertTo-Json -Depth 10

CodePudding user response:

so what if you skip the very last assignment and convert $step to JSON? like so:

$wizardDataArray = @{}
$stepTypeData =@{}
$step = New-Object System.Collections.ArrayList

$wizardData = @{"mode"="Add"; "resourceName"="basicServer";
"serverName"="demoServer"; "serverAddress"="xyz.abc.info";
"activeDbCatalog"="demodb";}

$stepData = @{"wizardType"="baseServer"; "wizardData"=$wizardData}

$stepTypeData = @{"stepType"="runWizard"; "stepData"=$stepData}
$step.Add(@{"steps"=$stepTypeData})


$step | ConvertTo-Json -Depth 10
  • Related