0

I have below Json file with content:

InitialApiConnectionTemplateFile.json:

{
    "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
    "contentVersion": "1.0.0.0",
    "parameters": {
        "connections_$APIConnectionName_name": {
            "defaultValue": "$APIConnectionName",
            "type": "String"
        }
    },
    "variables": {},
    "resources": []
}

The string $APIConnectionName which is I want to replace.

But I use the -replace like below:

$JsonData = Get-Content $(System.DefaultWorkingDirectory)\InitialApiConnectionTemplateFile.json | ConvertFrom-Json

$JsonData -replace '$APIConnectionName', 'TestValue'

$JsonDataNew = $JsonData | ConvertTo-Json -depth 100

Write-Host "$JsonDataNew "

But it wot work for me. Please help.

Joy
  • 1,171
  • 9
  • 15
  • Leave out the `ConvertFrom-Json` and `ConvertTo-Json`. You want to `-replace` in the string data, so there's no need to roundtrip through JSON -- and even if you wanted to do that, you'd need to perform the replace before the conversion. – Jeroen Mostert Mar 17 '23 at 08:42
  • @JeroenMostert, Thanks for your comment. Even if I remove the ConvertFrom-Json and ConvertTo-Json from the scripts, but it still not work. – Joy Mar 17 '23 at 08:46
  • `$JsonDataNew = (Get-Content -Path $(System.DefaultWorkingDirectory)\InitialApiConnectionTemplateFile.json -Raw) -replace '$APIConnectionName','TestValue'` – lit Mar 17 '23 at 10:12
  • 1
    It should be `-replace '\$APIConnectionName','TestValue'` (search pattern is RegEx, so you have to backslash-escape `$`). – zett42 Mar 17 '23 at 12:18
  • If the actual replacement value may contain [reserved JSON characters](https://stackoverflow.com/a/27516892/7571258), you have to escape them, e. g. `-replace '\$APIConnectionName', ($replacementValue | ConvertTo-Json).Trim('"')` – zett42 Mar 17 '23 at 12:28
  • @zett42, Your suggstion work for me, thanks. If you convert your comment to answer, I`d like to mark it as answer. – Joy Mar 20 '23 at 06:39

0 Answers0