jsonpowershell

Replace a character in a json file with powershell


In a json file i have this text

"result": "1:3",
"points": "29:37",

Now i want to change it with powershell to

"result": "1-3",
"points": "29-37",

How to do it? I guess I need som kind of regex to do it.


Solution

  • In general, for robustness it's better to use OO processing based on a JSON parser, namely ConvertFrom-Json, and later reconversion to JSON with ConvertTo-Json, as shown in Mathias' answer.

    In a pinch, you can use plain-text processing with a regex-based string replacement such as
    -replace '(?<="\d+):', '-'

    Applied to your case:

    $jsonFilePath = 'C:\myfile.json'
    (Get-Content -Raw $jsonFilePath) -replace '(?<="\d+):', '-' |
      Set-Content -NoNewLine $jsonFilePath