0

我在 Powershell 中有一个 PSCustomObject,我想将其转换为 JSON。Key-Value-Pair 应该在“children”数组下。你能帮我吗?

电源外壳:

#PowershellObject
$BookmarkContainer = [PSCustomObject]@{
    "roots" = @{
        "other" = @{
            "children" = @()
        }
        "bookmark_bar" = @{
            "children" = @()
            "name" ="FavouriteBar"
            "type" ="folder"
            
        }
    }
    "version"=1
}

JSON-输出:

{
    "roots":  {
        "bookmark_bar":  {
            "name":  "FavouriteBar",
            "type":  "folder",
            "children":  [ ]
        },
        "other":  {
            "children":  [ ]
        }
    },
    "version":  1
}

预期输出:

{
    "roots":  {
        "bookmark_bar":  {
            "children":  [ ],
            "name":  "FavouriteBar",
            "type":  "folder"
        },
        "other":  {
            "children":  [ ]
        }
    },
    "version":  1
}
4

1 回答 1

1

默认情况下,哈希表没有排序。使用该[ordered]属性来使用 OrderedDictionary。使用-Depth参数 onConvertTo-Json因为它的默认值是2并且你有超过 2 层的嵌套。

$BookmarkContainer = [PSCustomObject]@{
    "roots" = [ordered]@{
        "other" = @{
            "children" = @()
        }
        "bookmark_bar" = [ordered]@{
            "children" = @()
            "name" ="FavouriteBar"
            "type" ="folder"
            
        }
    }
    "version"=1
}

$BookmarkContainer | ConvertTo-Json -Depth 4

输出:

{
    "roots":  {
                  "other":  {
                                "children":  [

                                             ]
                            },
                  "bookmark_bar":  {
                                       "children":  [

                                                    ],
                                       "name":  "FavouriteBar",
                                       "type":  "folder"
                                   }
              },
    "version":  1
}
于 2021-10-05T13:07:32.893 回答