Unable to split yml object

Himanshuk 161 Reputation points
2021-02-22T13:05:04.117+00:00

I have used convert to yaml and convert json to yaml now I have say $a=$b.path.s.values="//server/main/builds" I want to replace /with \but not happen as it's yaml element $a=$b.path.s.values.replace("/","\") not working for yaml element

#the full code
$c=c:\temp\my.json
$b=gc $c -raw | out-string| convertfrom-json| convertto-yaml
$b=$b.convertfrom-yaml
$a=$b.path.s.values.replace("/","\")
My json like
{
Path:
S://server/mypath/subdir
}
Windows Server PowerShell
Windows Server PowerShell
Windows Server: A family of Microsoft server operating systems that support enterprise-level management, data storage, applications, and communications.PowerShell: A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
5,434 questions
{count} votes

3 answers

Sort by: Most helpful
  1. Rich Matheisen 45,416 Reputation points
    2021-02-22T15:31:47.653+00:00

    Why not deal with the output of ConvertFrom-Json and then, after making the substitution, send the object to the ConvertTo-Yaml?

    BTW, your "My json like" example is incorrect. You have to quote the value "S://server/mypath/subdir" or the "S:" will be taken as a JSON primitive and the conversion will fail.

    0 comments No comments

  2. Ian Xue (Shanghai Wicresoft Co., Ltd.) 32,326 Reputation points Microsoft Vendor
    2021-02-23T03:49:30.847+00:00

    Hi,

    Please check if this works. The first backslash is the "excape" character that makes the second backslash be seen as an ordinary character.

    $c="c:\temp\my.json"  
    $b=(gc $c -raw | out-string).replace("/","\\") | convertfrom-json| convertto-yaml  
    

    Best Regards,
    Ian Xue

    ============================================

    If the Answer is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


  3. Rich Matheisen 45,416 Reputation points
    2021-02-23T20:17:47.087+00:00

    Adjust this example to suit your requirements. It doesn't use YAML but you can pipe the "ConvertTo-JSON" into you "ConvertTo-YAML".

    $h = [ordered]@{
        Path = [ordered]@{S = "//server/mypath/subdir"}
        sub =  [ordered]@{O = "//another server/nextpath/file"}
    }
    $j = $h | ConvertTo-Json
    $j  # show JSON
    "===== ^^    ======= || OUT =============================="
    "===== || IN ======= vv =================================="
    $p = $j | ConvertFrom-Json  # convert JSON to Powershell CustomObject
    
    $parent = "Path"
    $child  = "S"
    $p.$parent.$child = $p.$parent.$child -replace "/","\"
    $p | ConvertTo-Json         # all single "\" will be escaped, so "\" becomes "\\" and "\\" becomes "\\\\"
    
    0 comments No comments