1

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?

1
  • 4
    Avoid piping the input: $myUpdatedTest = ConvertTo-Json -InputObject $myTest.Values Commented May 26, 2022 at 10:30

2 Answers 2

2

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?

Sign up to request clarification or add additional context in comments.

Comments

1

Kinda clunky, but this works:

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

if($myTest){

    if($myTest.Count -eq 1){

        $myUpdatedTest = "[$($myTest.Values | ConvertTo-Json -Compress)]"
    }else{

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

$myUpdatedTest

1 Comment

Thanks @nimizen, I wanted to avoid the if condition (should've mentioned in the question)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.