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
}
}
(Get-Content $jsonfile) -replace '(?<=^\s*"Version"\s*:\s*")[^"]*(?="\s*$)', '10' | Set-Content $jsonfile?$jsonfile = .\path\to\your\file.", the(?="\s*$)should be either(?=")or removed.