【问题标题】:& sign is converted into \u0026 through powershell& 符号通过powershell转换成\u0026
【发布时间】:2021-11-19 12:14:21
【问题描述】:

我有以下代码:

$getvalue= 'true&replicaSet=users-shard-0&authSource=adsfsdfin&readPreference=neasrest&maxPoolSize=50&minPoolSize=10&maxIdleTimeMS=60'
$getvalue = $getvalue -replace '&','&'
$pathToJson = 'C:\1\test.json'
$a = Get-content -Path $pathToJson | ConvertFrom-Json
$a.connectionStrings.serverstring=$getvalue
$a | ConvertTo-Json | Set-content $pathToJson -ErrorAction SilentlyContinue

我得到以下结果:

true\u0026replicaSet=users-shard-0\u0026authSource=adsfsdfin\u0026readPreference=neasrest\u0026maxPoolSize=50\u0026minPoolSize=10\u0026maxIdleTimeMS=60

&符号转换成\u0026。如何防止隐蔽值。 你可以参考这个question

我需要 & 登录 json 文件而不是 \u0026

【问题讨论】:

标签: json powershell


【解决方案1】:

Windows PowerShellConvertTo-Json 意外将 & 序列化为其等效的 Unicode 转义序列 (\u0026)'<> 也一样(幸运的是,在 PowerShell (Core) 7+ 中不再发生这种情况) - 虽然出乎意料且妨碍了可读性 - 这对于程序化处理来说不是问题,因为包括ConvertFrom-Json在内的JSON解析器确实可以识别这样的转义序列:

($json = 'a & b' | ConvertTo-Json) # -> `"a \u0026 b"` (WinPS)
ConvertFrom-Json $json # -> verbatim `a & b`, i.e. successful roundtrip

如果您确实想将此类转义序列转换为它们所代表的逐字字符

  • This answer 到链接的问题显示了一种稳健、通用的字符串替换方法

  • 但是,在您的情况下 - 鉴于您知道要替换的特定且唯一的 Unicode 序列,并且似乎没有误报的风险 - 您可以简单地使用 另一个 -replace 操作

$getvalue= 'true&replicaSet=users-shard-0&authSource=adsfsdfin&readPreference=neasrest&maxPoolSize=50&minPoolSize=10&maxIdleTimeMS=60'
$getvalue = $getvalue -replace '&','&'

# Simulate reading an object from a JSON
# and update one of its properties with the string of interest.
$a = [pscustomobject] @{
  connectionStrings = [pscustomobject] @{
    serverstring = $getValue
  }
} 

# Convert the object back to JSON and translate '\\u0026' into '&'.
# ... | Set-Content omitted for brevity.
($a | ConvertTo-Json) -replace '\\u0026', '&'

输出(注意\u0026 实例是如何被& 替换的):

{
  "connectionStrings": {
    "serverstring": "true&replicaSet=users-shard-0&authSource=adsfsdfin&readPreference=neasrest&maxPoolSize=50&minPoolSize=10&maxIdleTimeMS=60"
  }
}

您可以覆盖所有个有问题的字符 - & '<> - 使用 多个 -replace 操作:

  • 但是,如果您需要排除误报(例如,\\u0026),则需要来自aforementioned answer 的更复杂的解决方案。
# Note: Use only if false positives aren't a concern.

# Sample input string that serializes to:
#   "I\u0027m \u003cfine\u003e \u0026 dandy."
($json = "I'm <fine> & dandy." | ConvertTo-Json)

# Transform the Unicode escape sequences for chars. & ' < >
# back into those chars.
$json -replace '\\u0026', '&' -replace '\\u0027', "'" -replace '\\u003c', '<' -replace '\\u003e', '>'

【讨论】:

    猜你喜欢
    • 2012-09-24
    • 2014-08-17
    • 2014-05-07
    • 1970-01-01
    • 1970-01-01
    • 2022-01-22
    • 2020-04-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多