gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 00:12:52 24 4
gpt4 key购买 nike

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

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com