1

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 Answer 1

3

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"
              ]
}
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you but how do I add those brackets? JSON should look like this: Example: $nr2 = 145 JSON: { "value": ["E_145"] }
ConvertTo-Json should do that for you if value is an array, there is no need to do it yourself.
I've edited the answer and added a piece of code that shows that it works.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.