问题
I'm trying to pack my data into objects before displaying them with ConvertTo-Json
. The test case below shows perfectly how I'm dealing with data and what problem occurs:
$array = @("a","b","c")
$data = @{"sub" = @{"sub-sub" = $array}}
$output = @{"root" = $data}
ConvertTo-Json -InputObject $data
ConvertTo-Json -InputObject $output
Output (formatted by hand for clarity):
{ "sub": { "sub-sub": [ "a", "b", "c" ] }}
{ "root": { "sub": { "sub-sub": "a b c" } }}
Is there any way to assign $data
to $output
without this weird implicit casting?
回答1:
As mentioned in the comments, ConvertTo-Json
will try to flatten the object structure beyond a maximum nesting level, or depth, by converting whatever object it finds beyond that depth to a string.
The default depth is 2, but you can specify that it should go deeper with the Depth
parameter:
PS C:\> @{root=@{level1=@{level2=@("level3-1","level3-2")}}}|ConvertTo-Json
{
"root": {
"level1": {
"level2": "level3-1 level3-2"
}
}
}
PS C:\> @{root=@{level1=@{level2=@("level3-1","level3-2")}}}|ConvertTo-Json -Depth 3
{
"root": {
"level1": {
"level2": [
"level3-1",
"level3-2"
]
}
}
}
来源:https://stackoverflow.com/questions/36526972/unexpected-array-to-string-conversion