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

Time:10-23

I have a Json file having multiple comments and I want to replace a value in it.

I tried the below and it gives me a json file without comments. But I don't understand how to change the value and save it back with comments. Is this even possible because we are replacing all the comments with empty lines?

$json = Get-Content $jsonfile -Raw | ConvertFrom-Json
$configfile = $json -replace '(?m)(?<=^([^"]|"[^"]*")*)//.*' -replace '(?ms)/\*.*?\*/'

My config.json is as below and I want to change the value of "version" to 10 through a powershell script and then save it back with the comments intact.

    {
        "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
         }
}

CodePudding user response:

Use

(Get-Content test.txt) -replace '^(\s*"Version"\s*:\s*")[^"]*', '${1}10' | Set-Content test.txt

See proof.

EXPLANATION

--------------------------------------------------------------------------------
  ^                        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))
  • Related