我有一个文件,其中包含一些属性,其中某些属性的值包含转义符,例如一些Urls和Regex模式。
在读取内容并转换回json时,无论是否进行转义,内容都不正确。如果我使用转义转义转换回json,则某些正则表达式会中断;如果我使用转义转义转换,则url和某些正则表达式会中断。
我该如何解决这个问题?
最少完整的可验证示例
以下是一些简单的代码块,可让您简单地重现该问题:
内容
$fileContent =
@"
{
"something": "http://domain/?x=1&y=2",
"pattern": "^(?!(\\`|\\~|\\!|\\@|\\#|\\$|\\||\\\\|\\'|\\\")).*"
}
"@
Run Code Online (Sandbox Code Playgroud)
随着逃脱
如果我阅读了内容,然后使用以下命令将内容转换回json:
$fileContent | ConvertFrom-Json | ConvertTo-Json | %{[regex]::Unescape($_)}
Run Code Online (Sandbox Code Playgroud)
输出(错误)将是:
{
"something": "http://domain/?x=1&y=2",
"pattern": "^(?!(\|\~|\!|\@|\#|\$|\||\\|\'|\")).*"
}
Run Code Online (Sandbox Code Playgroud)
没有逃脱
如果我阅读了内容,然后使用以下命令将内容转换回json:
$fileContent | ConvertFrom-Json | ConvertTo-Json
Run Code Online (Sandbox Code Playgroud)
输出(错误)将是:
{
"something": "http://domain/?x=1\u0026y=2",
"pattern": "^(?!(\\|\\~|\\!|\\@|\\#|\\$|\\||\\\\|\\\u0027|\\\")).*"
}
Run Code Online (Sandbox Code Playgroud) powershell ×1