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

Using PowerShell how to replace and save a value in a json file having comments

我有一个包含多个评论的 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*")[^"]*', '10' | Set-Content test.txt

参见proof

解释

--------------------------------------------------------------------------------
  ^                        the beginning of the string
--------------------------------------------------------------------------------
  (                        group and capture to :
--------------------------------------------------------------------------------
    \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 
--------------------------------------------------------------------------------
  [^"]*                    any character except: '"' (0 or more times
                           (matching the most amount possible))