PowerShell添加JSON节点后格式错乱的解决方法
解决PowerShell修改JSON时的格式错乱与大小写异常问题
问题现象
使用PowerShell脚本向JSON文件的targetLocations数组添加新节点后,出现两个异常:
- JSON格式错乱,键值对冒号后出现大量多余空格
- 输入的节点名称(如
Australia)被自动转换为小写(australia)
原始JSON
{"$schema": "https://schema.json#", "contentVersion": "1.0.0.0", "parameters": {"existingGalleryName": {"value": "Gallery"}, "serviceArtifactName": {"value": "servicename"}, "location": {"value": "East US"}, "targetLocations": {"value": [{"name": "Qatar Central"}, {"name": "Central US EUAP"}, {"name": "East US 2 EUAP"}, {"name": "West Central US"}]}, "description": {"value": "Redis Service Artifact for Standard Customers without scheduled patch window"}}}
待添加节点
{"name": "Australia"}
预期输出
{"$schema": "https://schema.json#", "contentVersion": "1.0.0.0", "parameters": {"existingGalleryName": {"value": "Gallery"}, "serviceArtifactName": {"value": "servicename"}, "location": {"value": "East US"}, "targetLocations": {"value": [{"name": "Qatar Central"}, {"name": "Central US EUAP"}, {"name": "East US 2 EUAP"}, {"name": "West Central US"}, {"name": "Australia"}]}, "description": {"value": "Redis Service Artifact for Standard Customers without scheduled patch window"}}}
实际异常输出
{"$schema": "https://schema.json#", "contentVersion": "1.0.0.0", "parameters": {"existingGalleryName": {"value": "Gallery"}, "serviceArtifactName": {"value": "servicename"}, "location": {"value": "East US"}, "targetLocations": {"value": [{"name": "Qatar Central"}, {"name": "Central US EUAP"}, {"name": "East US 2 EUAP"}, {"name": "West Central US"}, {"name": "australia"}]}, "description": {"value": "Redis Service Artifact for Standard Customers without scheduled patch window"}}}
问题原因
- 多余空格:PowerShell的
ConvertTo-Json默认会生成带格式化空格的JSON,与原始紧凑格式不符 - 大小写异常:使用哈希表
@{name = ...}创建节点时,与原始JSON转换后的PSCustomObject类型不一致,触发了意外的大小写转换
修正后的脚本
function ServiceArtifact { param ( [string]$jsonFilePath, [string]$newLocationName ) # 读取JSON并转换为PSCustomObject $jsonContent = Get-Content -Path $jsonFilePath -Raw | ConvertFrom-Json # 创建与原始结构一致的PSCustomObject节点 $newLocation = [PSCustomObject]@{ name = $newLocationName } # 追加到目标数组 $jsonContent.parameters.targetLocations.value += $newLocation # 生成紧凑格式JSON,消除多余空格 $updatedJsonContent = $jsonContent | ConvertTo-Json -Depth 10 -Compress # 以UTF8编码写入文件,避免乱码 $updatedJsonContent | Set-Content -Path $jsonFilePath -Encoding UTF8 Write-Output "New location '$newLocationName' added successfully." } $filePath = "E:\vagrant-vms\temp\area.json" $newLocationName = Read-Host "Enter the location that you want to add" ServiceArtifact -jsonFilePath $filePath -newLocationName $newLocationName
关键改动说明
- 使用
PSCustomObject创建节点:确保新节点类型与原始JSON转换后的对象一致,彻底避免大小写异常问题 - 添加
-Compress参数:生成无多余空格的紧凑JSON,与原始格式保持一致 - 指定UTF8编码:防止写入文件时出现编码乱码,保证JSON内容的正确性
内容的提问来源于stack exchange,提问作者user9699822
相关产品推荐
相关产品推荐

