Home > Software design >  Powershell add column name to array data then convert it to JSON
Powershell add column name to array data then convert it to JSON

Time:10-12

Basically I formed an array of data based on certain conditions inside a loop and arrary data is something like this:

student1 RL123 S12 student2 RL423 S32 student6 RL166 S02 student34 RL993 P12 student99 RL923 S12

Above array data needs to be converted to JSON as below:

{
    "Name" : "student1"
    "RollNo" : "RL123"
    "SubjectID" : "S12"
},
{
    "Name" : "student2"
    "RollNo" : "RL423"
    "SubjectID" : "S32"
},
{
    "Name" : "student6"
    "RollNo" : "RL166"
    "SubjectID" : "S02"
},
{
    "Name" : "student34"
    "RollNo" : "RL993"
    "SubjectID" : "RL993"
},
{
    "Name" : "student99"
    "RollNo" : "RL923"
    "SubjectID" : "S12"
}

CodePudding user response:

If indeed your array is an array of strings (let's call it $students), you can skip the below line.

However, the way you have formatted it in your question makes it a string with space-separated items, so if that is the case, we should create a proper array from it by splitting on the whitespaces:

$students = 'student1 RL123 S12 student2 RL423 S32 student6 RL166 S02 student34 RL993 P12 student99 RL923 S12' -split '\s '

Now just iterate over the values in the array and create objects using 3 array elements on each object:

$data = for ($i = 0; $i -lt $students.Count; $i =3) {
    [PsCustomObject]@{
        Name      = $students[$i]
        RollNo    = $students[$i   1]
        SubjectID = $students[$i   2]
    }
}
# here you convert the object array to JSON
$data | ConvertTo-Json

Output:

[
    {
        "Name":  "student1",
        "RollNo":  "RL123",
        "SubjectID":  "S12"
    },
    {
        "Name":  "student2",
        "RollNo":  "RL423",
        "SubjectID":  "S32"
    },
    {
        "Name":  "student6",
        "RollNo":  "RL166",
        "SubjectID":  "S02"
    },
    {
        "Name":  "student34",
        "RollNo":  "RL993",
        "SubjectID":  "P12"
    },
    {
        "Name":  "student99",
        "RollNo":  "RL923",
        "SubjectID":  "S12"
    }
]

the opening [ and closing ] denote that we're dealing with an array in Json syntax

  • Related