You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用PowerShell编辑JSON:如何强制UrlListeners保持为数组?

解决PowerShell修改JSON数组时被转为字符串的问题

原始JSON文件结构

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

编写的PowerShell代码

$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

问题说明

运行上述代码后,JSON中的UrlListeners字段会被转换为字符串类型,而非预期的数组类型,需要强制保留数组结构。

解决方案

只需将赋值的目标值显式声明为单元素数组即可,PowerShell中使用@()语法包裹单个元素就能创建数组:

修改后的代码示例1

# 显式定义为单元素数组
$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

修改后的代码示例2(直接赋值)

$JsonFile = Get-Content $destinationDirectory\appsettings.json -raw | ConvertFrom-Json
# 直接赋值为单元素数组
$JsonFile.ApiSettings.UrlListeners = @("http://(Ipofmymachine):9000")
$JsonFile | ConvertTo-Json -Depth 9 | Set-Content $destinationDirectory\appsettings.json

原理说明

PowerShell中,若将单个字符串赋值给原本是数组类型的属性,会自动将其转换为标量值,最终ConvertTo-Json输出时就会变成字符串而非数组。通过@()显式声明为数组,就能让JSON序列化时保留数组结构。

内容的提问来源于stack exchange,提问作者user182595

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 19:25:22