问题描述
我有一个包含一些属性的文件,其中一些属性的值包含转义字符,例如一些 Urls 和 Regex 模式.
I have a file containing some properties which value of some of them contains escape characters, for example some Urls and Regex patterns.
读取内容并转换回json时,无论有没有转义,内容都不正确.如果我用非转义转换回 json,一些正则表达式会中断,如果我用非转义转换,urls 和一些正则表达式会中断.
When reading the content and converting back to the json, with or without unescaping, the content is not correct. If I convert back to json with unescaping, some regular expression break, if I convert with unescaping, urls and some regular expressions will break.
我该如何解决问题?
最小完整可验证示例
这里有一些简单的代码块,可以让您简单地重现问题:
Here are some simple code blocks to allow you simply reproduce the problem:
内容
$fileContent =
@"
{
"something": "http://domain/?x=1&y=2",
"pattern": "^(?!(\\`|\\~|\\!|\\@|\\#|\\$|\\||\\\\|\\'|\\\")).*"
}
"@
使用 Unescape
如果我阅读了内容,然后使用以下命令将内容转换回 json:
If I read the content and then convert the content back to json using following command:
$fileContent | ConvertFrom-Json | ConvertTo-Json | %{[regex]::Unescape($_)}
输出(这是错误的)将是:
The output (which is wrong) would be:
{
"something": "http://domain/?x=1&y=2",
"pattern": "^(?!(\|\~|\!|\@|\#|\$|\||\\|\'|\")).*"
}
没有 Unescape
如果我阅读了内容,然后使用以下命令将内容转换回 json:
If I read the content and then convert the content back to json using following command:
$fileContent | ConvertFrom-Json | ConvertTo-Json
输出(这是错误的)将是:
The output (which is wrong) would be:
{
"something": "http://domain/?x=1\u0026y=2",
"pattern": "^(?!(\\|\\~|\\!|\\@|\\#|\\$|\\||\\\\|\\\u0027|\\\")).*"
}
预期结果
预期结果应与输入文件内容相同.
The expected result should be same as the input file content.
推荐答案
我决定不使用 Unscape
,而是替换unicode \uxxxx
字符及其字符串值,现在它可以正常工作了:
I decided to not use Unscape
, instead replace the unicode \uxxxx
characters with their string values and now it works properly:
$fileContent =
@"
{
"something": "http://domain/?x=1&y=2",
"pattern": "^(?!(\\`|\\~|\\!|\\@|\\#|\\$|\\||\\\\|\\'|\\\")).*"
}
"@
$fileContent | ConvertFrom-Json | ConvertTo-Json | %{
[Regex]::Replace($_,
"\\u(?<Value>[a-zA-Z0-9]{4})", {
param($m) ([char]([int]::Parse($m.Groups['Value'].Value,
[System.Globalization.NumberStyles]::HexNumber))).ToString() } )}
生成预期输出:
{
"something": "http://domain/?x=1&y=\\2",
"pattern": "^(?!(\\|\\~|\\!|\\@|\\#|\\$|\\||\\\\|\\'|\\\")).*"
}
这篇关于ConvertTo-Json 和 ConvertFrom-Jason 带有特殊字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!