regex - Powershell JSON 转换删除 unicode 转义字符而不删除文字\n

标签 regex powershell arm-template azure-data-factory-2

我的问题类似于这个问题:

Json file to powershell and back to json file

在powershell中导入和导出ARM模板时,使用Convert-FromJsonConvert-ToJson , 引入 unicode 转义序列。

我用的代码here再次逃脱。

一些示例代码(为了清晰起见,多行):

$armADF = Get-Content -Path $armFile -Raw | ConvertFrom-Json
$armADFString = $armADF | ConvertTo-Json -Depth 50
$armADFString | 
    ForEach-Object { [System.Text.RegularExpressions.Regex]::Unescape($_) } | 
    Out-File $outputFile

Here's我一直在阅读的 doco Unescape
导致输出文件相同,除了文字 \n 的所有实例(在原始 JSON 文件中)变成了实际的回车。这打破了 ARM 模板。

如果我不包含 Unescape 代码,则 \n被保留,但 unicode 字符也被保留,这也破坏了 ARM 模板。

看来我需要预先转义 \n所以当我调用 Unescape 时,他们变成了漂亮的小人 \n .我已经尝试了一些事情,比如在调用 unescape 之前添加它。
$armADFString = $armADFString -replace("\\n","\u000A")

这没有给我我需要的结果。

有人遇到过这个问题并解决了吗?有什么成功的逃生艺术家吗?

最佳答案

我重读了 Unescape doco 并注意到它也基本上会删除领先的 \字符,所以我尝试了这个不太可能的代码:

$armADF = Get-Content -Path $armFile -Raw | ConvertFrom-Json
$armADFString = $armADF | ConvertTo-Json -Depth 50
$armADFString = $armADFString -replace("\\n","\\n")
$armADFString | 
    ForEach-Object { [System.Text.RegularExpressions.Regex]::Unescape($_) } | 
    Out-File $outputFile

当然 - 替换 \\n\\n完全有道理:|

很高兴有人提出更优雅的解决方案。

编辑:我正在部署本身基于 JSON 的 ADF ARM 模板。长话短说,我还发现我需要添加它以阻止它转义合法转义的引号:
$armADFString = $armADFString -replace('\\"','\\"')

关于regex - Powershell JSON 转换删除 unicode 转义字符而不删除文字\n,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56412782/

相关文章:

c# - 将 Regex.Matches 连接到一个字符串

PowerShell 变量冲突

powershell - 使用我自己的vhd在资源组中创建VM

azure-web-app-service - 如何输出通过 ARM 模板部署的应用服务的 IP 地址

javascript - 正则表达式检测奇数个连续引号

正则表达式匹配后面没有任何内容的字符串

powershell - 新的 AzResourceGroupDeployment : Cannot retrieve the dynamic parameters for the cmdlet

powershell - 通过脚本设置管道变量时,Azure DevOps 是否删除引号?

java - 从 Java 请求中提取变量的正则表达式

powershell - 移动项路径作为变量