Home > front end >  Editing a JSON with PowerShell
Editing a JSON with PowerShell

Time:10-14

I have a json that looks something this

{
"ApiSettings": {
    "EnableSwagger": true,
    "UrlListeners": [
        "http://localhost:9000"
    ],
    "DebugMode":  true
},
}

And have some powershell that looks like this:

$UrlListeners = "http://(Ipofmymachine):9000"
$JsonFile = Get-Content $destinationDirectory\appsettings.json -raw | ConvertFrom-Json
$JsonFile.ApiSettings.UrlListeners = $UrlListeners
$JsonFile | ConvertTo-Json -Depth 9 | Set-Content $destinationDirectory\appsettings.json

The issue is that when the PowerShell is ran it converts the UrlListeners in the appsettings.json into a string, whereas it needs to stay as an array. Is there a way to force this value as an array?

Thanks

CodePudding user response:

ConvertFrom-Json and ConvertTo-Json doesn't change UrlListeners to string, you do :).

Use this instead: $JsonFile.ApiSettings.UrlListeners = @($UrlListeners)

CodePudding user response:

convertfrom-json converts correctly:

PS C:\Users\adm> $x = '{
>> "ApiSettings": {
>>     "EnableSwagger": true,
>>     "UrlListeners": [
>>         "http://localhost:9000"
>>     ],
>>     "DebugMode":  true
>> }
>> }' | ConvertFrom-Json

$x.ApiSettings.UrlListeners.gettype()

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     Object[]                                 System.Array

The problem is that you do:

$JsonFile.ApiSettings.UrlListeners = $UrlListeners

This changes the datatype to String. You should do:

$x.ApiSettings.UrlListeners  = $UrlListeners

or:

$x.ApiSettings.UrlListeners = @($UrlListeners)
  • Related