簡體   English   中英

使用 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*")[^"]*', '${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))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM