How to add keys to values and convert to json in PowerShell?

1608 views json

I have a string like this:

$string = "PackageName1,1,C:\Path

(is a file with multilines, when I get the content I have the string above)

I want to convert this string to Json:

       Pacakge: "PackageName1",
       Branch: = "1",
       LocalPath = "C:\Path"

       Pacakge: "PackageName2",
       Branch: = "2",
       LocalPath = "C:\Path2"

I can get the values with this code:

$spiltted = $string.Split(' ')

ForEach ($s in $splitted)
   $values = $s.Split(',')

How can I add the Json keys to each value and convert it to Json object?

Thank you.

answered question

1 Answer


As your String looks like a csv without headers:

 $string | ConvertFrom-Csv -Header Package,Branch,LocalPath|ConvertTo-Json

Sample output

        "Package":  "PackageName1",
        "Branch":  "1",
        "LocalPath":  "C:\\Path"
        "Package":  "PackageName2",
        "Branch":  "12",
        "LocalPath":  "C:\\Path2"
        "Package":  "PackageName3",
        "Branch":  "3",
        "LocalPath":  "C:\\Path3"

posted this

Have an answer?


Please login first before posting an answer.