通过排序将 Powershell 对象转换为 JSON

Convert a Powershell-Object to JSON with sorting

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

Powershell:

#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
}

哈希表默认不排序。使用 [ordered] 属性来改为使用 OrderedDictionary。在 ConvertTo-Json 上使用 -Depth 参数,因为它的默认值是 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
}