Home > Back-end >  Write JSON Array without flattening list to a file in PowerShell
Write JSON Array without flattening list to a file in PowerShell

Time:12-02

I have created below JSON array in PowerShell

$json = @(
        @{
            firstname = "abc"
            lastname = "xyz"
            email = "[email protected]"           
        }
    )

When I write json to a file list/array structure is lost $json | ConvertTo-Json | Set-Content $filepath $json | ConvertTo-Json | Out-File $filePath I tried with the above commands, file looks like this

{
  "firstname": "abc",
  "lastname": "xyz",
   "email": "[email protected]"
}

I want to write json to a file without flattening the list i.e. retain the array format as shown below

[
  {
     "firstname": "abc",
      "lastname": "xyz",
       "email": "[email protected]"
  }
]

CodePudding user response:

The pipeline will flatten/unravel the array stored in $json, so avoid piping to ConvertTo-Json at all:

ConvertTo-Json $json |Out-File $path
  • Related