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

PowerShell中单元素数组序列化问题及函数适配疑问

PowerShell单元素JSON数组合并后序列化问题的解决方案

问题背景

你编写了读取JSON文件的PowerShell函数:

function Get-JsonContent{
  param (
    [Parameter(
      Mandatory = $true,
      HelpMessage = "Path to the json config file."
    )]
    [string] $Filepath
  )
  $content = Get-Content -Path $Filepath -Raw
  $config = $content | ConvertFrom-Json -NoEnumerate
  return $config
}

使用-NoEnumerate参数在PowerShell 7+中可解决单元素JSON数组被转为单个对象的问题,但仅在直接管道传递给ConvertTo-Json时有效。当读取两个JSON文件合并内容后再序列化,该方法失效;而使用-Array参数会将所有非数组对象也转为数组,不符合需求。

解决方案

方法1:使用System.Text.Json替代PowerShell内置命令

PowerShell内置的ConvertFrom-Json/ConvertTo-Json在单元素数组的类型保留上存在局限性,改用.NET的System.Text.Json组件可精准处理JSON结构,确保数组类型(包括单元素数组)在合并和序列化过程中不丢失。

改写读取函数

function Get-JsonContent{
  param (
    [Parameter(
      Mandatory = $true,
      HelpMessage = "Path to the json config file."
    )]
    [string] $Filepath
  )
  $jsonString = Get-Content -Path $Filepath -Raw
  # 使用System.Text.Json反序列化,保留原始类型结构
  return [System.Text.Json.JsonSerializer]::Deserialize($jsonString, [object])
}

合并并序列化

读取两个JSON文件合并后,用System.Text.Json序列化:

# 读取两个JSON文件
$json1 = Get-JsonContent "file1.json"
$json2 = Get-JsonContent "file2.json"

# 合并内容(示例为合并属性,可根据实际需求调整)
$merged = [PSCustomObject]@{
    ConfigA = $json1.ConfigA
    ConfigB = $json2.ConfigB
}

# 序列化为JSON,保留数组结构
$serializedJson = [System.Text.Json.JsonSerializer]::Serialize($merged, [System.Text.Json.JsonSerializerOptions]@{
    WriteIndented = $true # 格式化输出,可选
})

# 输出或保存结果
$serializedJson | Out-File "merged.json"

方法2:手动检查并强制数组类型(适用于必须使用内置命令的场景)

如果必须使用PowerShell内置的JSON命令,合并后需手动检查属性类型,将原本应为数组的单元素对象强制转为数组:

# 读取并合并内容
$json1 = Get-JsonContent "file1.json"
$json2 = Get-JsonContent "file2.json"
$merged = [PSCustomObject]@{
    Items = $json1.Items
    Settings = $json2.Settings
}

# 遍历属性,检查并强制数组类型(示例针对Items属性)
if ($merged.Items -and $merged.Items -isnot [array]) {
    $merged.Items = @($merged.Items)
}

# 序列化
$merged | ConvertTo-Json -Depth 10

注意:此方法需要明确知道哪些属性应为数组,适合结构固定的JSON场景;如果JSON结构不固定,推荐使用方法1。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 22:01:12