gpt4 book ai didi

json - 使用 PowerShell 如何在具有注释的 json 文件中替换和保存值

转载 作者:行者123 更新时间:2023-12-04 13:24:10 29 4
gpt4 key购买 nike

我有一个包含多个注释的 Json 文件,我想替换其中的一个值。
我尝试了下面的方法,它给了我一个没有注释的 json 文件。但我不明白如何更改该值并将其与注释一起保存。这甚至可能因为我们用空行替换所有评论吗?

$json = Get-Content $jsonfile -Raw | ConvertFrom-Json
$configfile = $json -replace '(?m)(?<=^([^"]|"[^"]*")*)//.*' -replace '(?ms)/\*.*?\*/'
我的 config.json 如下所示,我想通过 powershell 脚本将“version”的值更改为 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
proof .
说明
--------------------------------------------------------------------------------
^ 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))

关于json - 使用 PowerShell 如何在具有注释的 json 文件中替换和保存值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69683137/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com