如何用PowerShell修改JSON中games的points差值及解决脚本无效问题
PowerShell修改JSON中points字段值的问题解决
问题背景
需要修改JSON文件中disciplin数组下games子数组内的points字段值:将"数字:数字"格式的字符串转换为两个数字的差值(例如"48:35"改为13,"31:33"改为-2),但运行自行编写的PowerShell脚本后,输出文件与原文件完全一致,未达到预期效果。
原JSON结构
{ "disciplin": [ { "name": "Playoff", "teamsize": 2, "gender": 3, "system": 32, "status": 2, "id": 1, "games": [ { "result": "4:0", "points": "48:35", "id": 1 }, { "result": "4:0", "points": "31:33", "id": 2 } ] } ] }
用户尝试的PowerShell脚本
($json = Get-Content -Raw C:\Users\[USER]\Documents\file.json | ConvertFrom-Json) $json -replace '(?"points":\s*")(\d+):(\d+)(?=")', { [int] $_.Groups[1].Value - $_.Groups[2].Value } $json | ConvertTo-Json -depth 8 | Out-File "C:\Users\[USER]\Documents\new.json"
原脚本问题排查
- 对象与字符串操作混淆:
ConvertFrom-Json返回的是PSCustomObject类型的对象,而-replace是针对字符串的操作。直接对$json对象使用-replace不会修改原对象,仅返回无意义的字符串,且该结果未被赋值或使用,完全无效。 - 未修改原对象:脚本最后仍然使用原始的
$json对象转换为JSON输出,自然不会有任何修改内容。
正确实现脚本
通过遍历JSON对象的层级结构,直接修改对应字段的值:
# 读取并解析JSON文件 $json = Get-Content -Raw C:\Users\[USER]\Documents\file.json | ConvertFrom-Json # 遍历每个disciplin项 foreach ($discipline in $json.disciplin) { # 遍历当前disciplin下的每个game foreach ($game in $discipline.games) { # 拆分points字段的两个数字 $num1, $num2 = $game.points -split ':' # 计算差值并赋值回points字段 $game.points = [int]$num1 - [int]$num2 } } # 将修改后的对象转换为JSON并输出到文件 $json | ConvertTo-Json -Depth 8 | Out-File "C:\Users\[USER]\Documents\new.json"
内容的提问来源于stack exchange,提问作者Anders
相关产品推荐
相关产品推荐

