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

如何用PowerShell为CSV文本添加引号及解决JSON格式化问题

解决CSV列元素单独加引号及转JSON数组的问题

需求说明

  • 给CSV文件中AllowHosts列(逗号分隔的服务器名)和SPNs列的每个子字符串单独添加引号,而非给整列内容加外层引号
  • 将CSV转为JSON时,AllowHosts必须是数组类型,每个服务器名作为独立的带引号元素,不能把整列内容当成单个字符串

原始数据与错误尝试

原始CSV示例

ID,AllowHosts,SPNs,Description
1,server01,http/server01.example.com,Web Server
2,server02,server03,http/server02.example.com,http/server03.example.com,Cluster Server

错误脚本(达不到预期的原因)

# 错误:直接给整列内容加引号,转JSON后是单个字符串
$csv = Import-Csv -Path "input.csv"
$csv | ForEach-Object {
    $_.AllowHosts = "`"$($_.AllowHosts)`""
    $_.SPNs = "`"$($_.SPNs)`""
} | Export-Csv -Path "wrong_output.csv" -NoTypeInformation

# 转JSON错误:AllowHosts是字符串而非数组
$csv | ConvertTo-Json

这个脚本会把AllowHosts变成"server02,server03",转JSON后也是"AllowHosts": "server02,server03",完全不符合需求。

正确解决方案

1. 处理CSV:给每个子字符串单独加引号

先拆分逗号分隔的内容,给每个元素加引号后再拼接,最后导出符合要求的CSV:

# 导入原始CSV
$originalCsv = Import-Csv -Path "input.csv"

# 逐行处理列内容
$processedCsv = $originalCsv | ForEach-Object {
    # 处理AllowHosts:拆分每个服务器名,清理空格后加引号
    if ($_.AllowHosts -match '\S') {
        $_.AllowHosts = ($_.AllowHosts -split ',' | ForEach-Object { "`"$($_.Trim())`"" }) -join ','
    }
    # 处理SPNs:同AllowHosts逻辑
    if ($_.SPNs -match '\S') {
        $_.SPNs = ($_.SPNs -split ',' | ForEach-Object { "`"$($_.Trim())`"" }) -join ','
    }
    $_ # 返回处理后的行对象
}

# 导出格式化后的CSV,UseQuotes AsNeeded会自动处理字段的外层引号
$processedCsv | Export-Csv -Path "formatted_output.csv" -NoTypeInformation -UseQuotes AsNeeded

2. CSV转JSON:生成AllowHosts数组

要先把AllowHosts从逗号分隔的字符串转换成字符串数组,再转JSON才能得到预期格式:

# 准备JSON转换用的数据,将AllowHosts转为数组
$jsonData = $originalCsv | ForEach-Object {
    [PSCustomObject]@{
        ID          = $_.ID
        # 拆分AllowHosts为数组,空值则返回空数组
        AllowHosts  = if ($_.AllowHosts -match '\S') { $_.AllowHosts -split ',' | ForEach-Object { $_.Trim() } } else { @() }
        SPNs        = $_.SPNs
        Description = $_.Description
    }
}

# 转换为JSON,-Depth确保嵌套结构正确输出
$jsonData | ConvertTo-Json -Depth 10

预期输出示例

处理后的CSV

ID,AllowHosts,SPNs,Description
1,"""server01""","""http/server01.example.com""",Web Server
2,"""server02"",""server03""","""http/server02.example.com"",""http/server03.example.com""",Cluster Server

注:CSV标准中,包含引号的字段会被外层引号包裹,内部引号会转义为双引号,这是正常格式。

转换后的JSON

[
    {
        "ID": "1",
        "AllowHosts": [
            "server01"
        ],
        "SPNs": "http/server01.example.com",
        "Description": "Web Server"
    },
    {
        "ID": "2",
        "AllowHosts": [
            "server02",
            "server03"
        ],
        "SPNs": "http/server02.example.com,http/server03.example.com",
        "Description": "Cluster Server"
    }
]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 01:50:28