如何用PowerShell向JSON文件新增键值对且避免无关空格与全文件重写
问题解答
1. 有没有避免无关空格的正确实现方式?
有两种实用方案:
- 匹配原文件缩进参数:先确认原JSON的缩进规则(你的示例用4个空格),修改对象后用
ConvertTo-Json指定对应缩进,同时保证读写编码一致。示例代码:$FilePath = 'C:\Users\test.json' # 加-Raw避免读取时拆分换行 $jsonObj = Get-Content $FilePath -Raw | ConvertFrom-Json # 直接构造PS对象,比拼接JSON字符串更可靠 $q3 = [PSCustomObject]@{ question = "12 - 6 = ?" options = @("1", "2", "3", "6") answer = "6" } $jsonObj.quiz.maths | Add-Member -NotePropertyName "q3" -NotePropertyValue $q3 # 指定4空格缩进,编码用UTF8匹配原文件 $jsonObj | ConvertTo-Json -Depth 3 -Indent 4 | Set-Content $FilePath -Encoding UTF8 - 用第三方模块格式化:安装
PSJsonFormatter模块(Install-Module -Name PSJsonFormatter -Scope CurrentUser),它能更好地对齐原文件格式:
这两种方式都能大幅减少无意义的空格变更,基本能和原文件格式对齐。$FilePath = 'C:\Users\test.json' $jsonObj = Get-Content $FilePath -Raw | ConvertFrom-Json $jsonObj.quiz.maths.q3 = [PSCustomObject]@{ question = "12 - 6 = ?" options = @("1", "2", "3", "6") answer = "6" } $jsonObj | ConvertTo-Json -Depth 3 | Format-Json -Indentation 4 | Set-Content $FilePath -Encoding UTF8
2. 能不能不转PowerShell对象,用-Raw读字符串添加属性?
可以,但这种方式非常脆弱,只适合固定结构的JSON,稍微一点格式变化就会出错。核心思路是精准定位插入位置,拼接字符串。针对你的示例JSON,代码如下:
$FilePath = 'C:\Users\test.json' $rawJson = Get-Content $FilePath -Raw # 构造匹配原格式的q3字符串 $q3Str = @" "q3": { "question": "12 - 6 = ?", "options": [ "1", "2", "3", "6" ], "answer": "6" } "@ # 替换maths节点的闭合位置,插入q3 $updatedJson = $rawJson -replace '( }\s* })', "$q3Str`n }`n }" $updatedJson | Set-Content $FilePath -Encoding UTF8
这种方法只会修改需要的部分,提交时只会显示q3的变更,但维护成本极高,不推荐用于复杂或经常变动的JSON文件。
3. 还有其他PowerShell方法添加新值吗?
有两种更专业的方式:
- 用Json.NET(Newtonsoft.Json)处理:这是行业标准的JSON库,能精准保留原文件格式。先安装包(
Install-Package Newtonsoft.Json -Scope CurrentUser),然后代码:$FilePath = 'C:\Users\test.json' $json = [Newtonsoft.Json.Linq.JObject]::Parse((Get-Content $FilePath -Raw)) $q3 = [Newtonsoft.Json.Linq.JObject]@{ question = "12 - 6 = ?" options = [Newtonsoft.Json.Linq.JArray]@("1", "2", "3", "6") answer = "6" } $json["quiz"]["maths"]["q3"] = $q3 # 保存时保留原缩进格式 $json.Save($FilePath, [Newtonsoft.Json.Formatting]::Indented) - 调用外部工具jq:如果安装了jq(轻量级JSON处理工具),可以用PowerShell调用它修改,格式控制更灵活:
$FilePath = 'C:\Users\test.json' # 添加q3并指定4空格缩进匹配原文件 jq --indent 4 '.quiz.maths.q3 = {"question": "12 - 6 = ?", "options": ["1","2","3","6"], "answer": "6"}' $FilePath | Set-Content $FilePath -Encoding UTF8
内容的提问来源于stack exchange,提问作者Chethiya Amarasinghe
相关产品推荐
相关产品推荐

