4

I want to displaying data from json to env file with this output

OnSubscription=True; Name=John; Surname=Smith 

but when I create data, its showing like this

@{OnSubscription=True; Name=John; Surname=Smith} 

and this is my script

$Path2 = ".\output\env"
$x = Get-Content .\basket.json| ConvertFrom-Json

foreach( $rootProperty in @($x.psobject.properties | where-object {$_.MemberType -eq "NoteProperty"}) )
{

    write-host "'$($rootProperty.Name)' = '$($rootProperty.Value)'"

    foreach( $childProperty in @($rootProperty.Value.psobject.properties | where-object {$_.MemberType -eq "NoteProperty"}) )
    {
        write-host "'$($childProperty.Name)' = '$($childProperty.Value)'"
         
        
    }

    $result = Add-Content -Path  $Path2 "$($rootProperty.Value) "

    $result = Add-Content -Path  $Path2 "$($childProperty.Value) " 

}

This is my sample of json

{
    "Customer":  {
                     "OnSubscription":  true,
                     "Name":  "John",
                     "Surname":  "Smith"
                 },
    "Data":  {
                 "Basket":  [
                                "apples",
                                "pears",
                                "oranges",
                                "strawberries"
                            ]
             }
}

How to remove this @{} ? I already follow this example Create .env file from a .json file but with power shell

Blanc Chen
  • 418
  • 4
  • 15
  • When you say that your output should be `OnSubscription=True; Name=John; Surname=Smith` do you mean that literal or the semicolons are meant to be new lines? Also your way of exporting data doesn't make much sense. – Santiago Squarzon Jun 21 '21 at 05:59
  • yes the output should be OnSubscription=True; Name=John; Surname=Smith on env file. My problem only the output using @{ } – Blanc Chen Jun 21 '21 at 06:00

1 Answers1

3

Try this:

$json = @'
{
    "Customer": {
        "OnSubscription":  true,
        "Name":  "John",
        "Surname":  "Smith"
    },
    "Data": {
        "Basket": [
            "apples",
            "pears",
            "oranges",
            "strawberries"
        ]
    }
}
'@ | ConvertFrom-Json

$output = ($json.Customer.PSObject.Properties.Name | ForEach-Object {
    "$_={0}" -f $json.Customer.$_
}) -join '; '

$Path2 = ".\output\env"
$output | Out-File $path
  • From File:
$json = Get-Content .\basket.json -Raw | ConvertFrom-Json
$output = ($json.Customer.PSObject.Properties.Name | ForEach-Object {
    "$_={0}" -f $json.Customer.$_
}) -join '; '

$Path2 = ".\output\env"
$output | Out-File $path
Santiago Squarzon
  • 41,465
  • 5
  • 14
  • 37