Search code examples
arrayspowershellhashtablekey-value

How to get the value as an array of strings from powershell hashtable


I have an array of hash table containing key value pairs, like below:

$myTest = @{};
$test1 = @{
    Name = "Food1"
    Value = "Sandwich"
    }
    $test2 = @{
    Name = "Food2"
    Value = "Salad"
    }
$myTest["Food1"] = $test1;
$myTest["Food2"] = $test2

On running the command $myUpdatedTest = $myTest.Values | ConvertTo-Json -Compress

gives the value in $myUpdatedTest --> [{"Value":"Sandwich","Name":"Food1"},{"Value":"Salad","Name":"Food2"}]

And if I have only $test1 added to the $myTest then the value comes in as {"Value":"Sandwich","Name":"Food1"} But in the later case I want the value to be inside [] --> [{"Value":"Sandwich","Name":"Food1"}] is there a way to achieve this?


Solution

  • The issue with this is how you are sending the object to the ConvertTo-Json cmdlet.

    I managed to get this working by changing

    $myUpdatedTest = $myTest.Values | ConvertTo-Json -Compress
    

    to

    $myUpdatedTest = ConvertTo-Json -Compress -InputObject $myTest.Values
    

    This then evaluates the whole $myTest.Values object as opposed to each value one by one. I hope this makes sense?