Search code examples
jsonpowershelladditionbracketssquare-bracket

Add square brackets while convert it to json in powershell


I am taking the parameters from TemplateJSON file and reading data from CSV file and the converting it to JSON again.

TemplateJSON:
{
      "adhocUARs":[
        ""
      ],
      "rolefullpath": ""
    }

CSV File: 
RoleFullPath,ResourceName
FolderName\ABCD,ABCD User Account Resource

I am getting the output in this format (without the square brackets):

NEWJSON:
    {
    "adhocUARs":"ABCD User Account Resource",
     "rolefullpath": "xyz"  
    }

But I expect the output to be in the following format(with the square brackets):

 NEWJSON:
   {
      "adhocUARs":["ABCD User Account Resource"]    
      "rolefullpath": "xyz"     
   }

Code used:

$TemplateJSON = Convertfrom-json ([IO.File]::ReadAllText("TemplateJSON.json"))
$RoleFile = Import-CSV "CSVFile.csv" -Delimiter ','
[int]$Row = 0

Foreach ($Line in $RoleFile)
{    
    $Row = $Row + 1
    $NewJSON = $TemplateJSON
    $NewJSON.adhocUARs =  $Line.ResourceName
    $NewJSON.roleFullPath= $Line.RoleFullPath    

    $RolePath = "D:\\DummyFolder\"
    $JSONPath = $RolePath + "patch.json"  
    Convertto-JSON $NewJSON | Out-file -Encoding "UTF8" $JSONPath
 }

What am I missing?gr


Solution

  • so in JSON the [ ] is an array. Currently you have $NewJSON.adhocUARs as a string single value. A simple solution would be :

    $NewJSON.adhocUARs =  @($Line.ResourceName)