我有一个Json文件有多个注释,我想替换其中的值。
我尝试了下面,它给了我一个没有注释的json文件。但我不明白如何更改值并将其保存回注释。因为我们用空行替换了所有的注释,这可能吗?
$json = Get-Content $jsonfile -Raw | ConvertFrom-Json
$configfile = $json -replace '(?m)(?<=^([^"]|"[^"]*")*)//.*' -replace '(?ms)/*.*?*/'
我的配置。json如下所示,我想更改"version"的值通过powershell脚本执行10,然后保存它并保留注释。
{
"FramewokSettings": {
"Name": "VX",
"Version": "8", // The value here is not constant. It can be something like v1.4.56.456 also
"GitVersion": "v5",
"DatabaseVersion": "7",
// Doing xyz
"CounterVersion": "2"
// Doing ABC.
// Start
}
}
使用
(Get-Content test.txt) -replace '^(s*"Version"s*:s*")[^"]*', '${1}10' | Set-Content test.txt
看到证据。
--------------------------------------------------------------------------------
^ the beginning of the string
--------------------------------------------------------------------------------
( group and capture to $1:
--------------------------------------------------------------------------------
s* whitespace (0 or more times (matching the most
amount possible))
--------------------------------------------------------------------------------
"Version" '"Version"'
--------------------------------------------------------------------------------
s* whitespace (0 or more times (matching the most
amount possible))
--------------------------------------------------------------------------------
: ':'
--------------------------------------------------------------------------------
s* whitespace (0 or more times (matching the most
amount possible))
--------------------------------------------------------------------------------
" '"'
--------------------------------------------------------------------------------
) end of $1
--------------------------------------------------------------------------------
[^"]* any character except: '"' (0 or more times
(matching the most amount possible))