Home > Enterprise >  How can we create dynamic json object in powershell
How can we create dynamic json object in powershell

Time:04-09

I am creating powershell script which generation json file where i want to create json object runtime based on mentioned name in $env variable and put some value inside it as json.

$env="prd,test,dev,..,...." # there are total 15 env & $env has 1 and more env.

Desire JSON :

{
 
   "prd" : {
         "Sid": "xxxxxx" }
   "test" : {
         "Sid": "xxx" }

   "So on" : {}
}

Trying to write script:

$env="prd,test,..,...,.."

$env=$env - split ","
For ( $i = 0 $i -le ($env.length -1) ;$i =1){

    $env[$i] = New-object System.Collection.ArrayList

    $env[$i].add("anydata10")

}

But this approach not working well since $env variable has any 1 or more env value.

In the powershell, can we create dynamic json object at runtime and any other approch to archive it ?

CodePudding user response:

For the root-level object ({"prd":{...}, "test":{...}}), I'd suggest an ordered dictionary, then create a custom object with the Sid property for each property:

# prepare env keys
$environments = "prd,test,dev,stg,qa" -split ","

# create ordered dictionary
$jsonObject = [ordered]@{}

foreach($envName in $environments){
    # create 1 property, the value of which will be an object with a `Sid` property
    $jsonObject[$envName] = [pscustomobject]@{
        # resolve the correct `Sid` value from somewhere
        Sid = Get-SidForEnv $envName
    }
}

# convert the whole thing to json
$jsonObject |ConvertTo-Json -Depth 3

Based on your comments about getting the correct sid value "from somewhere", I assume you already have a function that translates prd to prodsid1 and so forth, so simply replace Get-SidForEnv with whatever function that is :)

CodePudding user response:

I'm not sure I understand what you're trying to achieve. You can access environment variables using $env. So, if you have those values prd,test,... in some environment variable and you want to generate new environment variables based on those, you can do it like this:

#  $env:foo contains 'prd,test'
$env:foo -split ',' | % {
  New-Item -Path Env: -Name $_ -Value (@("anydata10") | ConvertTo-Json)  
}

  • Related