【问题标题】:Convert a Powershell-Object to JSON with sorting通过排序将 Powershell 对象转换为 JSON
【发布时间】:2021-11-25 18:15:51
【问题描述】:

我在 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。
  • @AdminOfThings 所说的。或者将内部项目转换为[pscustomobject](也将保留语法顺序)

标签: json powershell convertto-json


【解决方案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
}

【讨论】:

    猜你喜欢
    • 2016-12-24
    • 2021-10-30
    • 1970-01-01
    • 1970-01-01
    • 2018-01-29
    • 2020-09-11
    • 2017-08-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多