1

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

1
  • You should actually change the item ([0]), not the whole (parent) array: $JsonFile.ApiSettings.UrlListeners[0] = $UrlListeners Commented Oct 14, 2022 at 11:39

2 Answers 2

1

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

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

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your response, it will be set as my answer. Would you be able to explain why that works? What is that notation used? I'd like to know the why, not just the how. Thanks
@user182595 @() is array expression operator, it ensures that the output will be an array, even if it's empty or single element
0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.