英文:
how to prevent PowerShell adding \ to a string
问题
PowerShell is escaping the double quotes and backslashes in your string, which is why you see the extra backslashes in your JSON. To prevent PowerShell from adding these escape characters, you can use single quotes instead of double quotes when constructing your JSON string. Here's the modified part of your script:
Replace this line:
$a.value= "[`"E_" + $nr2 + "`"]"
With this line:
$a.value= '[\"E_' + $nr2 + '\"]'
By using single quotes, PowerShell will treat the string as-is and won't escape the double quotes and backslashes within it. This should give you the desired JSON format without the extra backslashes.
英文:
I'm currently working with Powershell editing JSONs
My JSON looks like this:
{
"value": ["E_"]
}
I only want to add a specific number after E_
.
The result should look like this:
{
"value": ["E_5"]
}
My PS Script:
$tdePath = 'C:\temp\tde.csv'
$dirName = Get-ChildItem -Path $rootDir -Filter TDE_Config.json -Recurse -ErrorAction SilentlyContinue -Force | Select-Object DirectoryName | Export-Csv $tdePath -NoTypeInformation
$importTDEJson = Import-Csv $tdePath -Encoding UTF8 | % {
[String]$nr = $_.DirectoryName.Split('\')[6].split(' ')[4]
$full_path = $_.DirectoryName + "\TDE_Config.json"
[int]$nr2 = $nr -as [int] #Convert String to Int to convert 004 -> 4
$a = Get-Content $full_path -raw | ConvertFrom-Json
$a.value= "[`"E_" + $nr2 + "`"]"
$a | ConvertTo-Json | set-content $full_path -Force
}
Only excuting "[`"E_" + $nr2 + "`"]"
returns the value I need.
For example if $nr2 = 145
it returns in ps console
["E_145"]
But my JSON looks like this:
{
"value": "[\"E_145\"]"
}
Why is powershell adding \ to my string?
How can I prevent powershell adding \ to my string?
答案1
得分: 3
只返回翻译好的部分:
您正在手动混合使用 JSON 和 ConvertTo-Json
。PowerShell 正在对您插入的反斜杠进行 JavaScript 转义。只需像这样设置 $a.value
:
$a.value = @("E_$nr2")
这将创建一个数组,然后 JSON 转换将为您完成其余部分。
编辑:
这是一个概念验证示例:
$a = [pscustomobject]@{
value = 'Something else'
}
$nr2 = 145
$a.value = @("E_$nr2")
$a | ConvertTo-Json
输出:
{
"value": [
"E_145"
]
}
英文:
You are mixing Json by hand and Json by ConvertTo-Json
.
Powershell is doing javascript escaping of the backslashes you insert. Just set $a.value
like this:
$a.value= @("E_$nr2")
That will create an array and the Json conversion will do the rest for you.
EDIT:
Here is a proof of concept:
$a = [pscustomobject]@{
value = 'Something else'
}
$nr2 = 145
$a.value= @("E_$nr2")
$a | ConvertTo-Json
outputs:
{
"value": [
"E_145"
]
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论