Search code examples
jsonpowershelljsonconvert

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


I have a string like this:

$string = "PackageName1,1,C:\Path
PackageName2,12,C:\Path2
PackageName3,3,C:\Path3"

(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.


Solution

  • 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"
        }
    ]