【问题标题】:Keep order of elements when parsing json and writing it back out解析 json 并将其写回时保持元素的顺序
【发布时间】:2022-08-18 22:16:01
【问题描述】:

我正在阅读一个 json 文件。更新一些值并将其写回。有些元素最终会出现乱序。

$manifest = (gc $manifestPath -raw) | ConvertFrom-Json -AsHashtable
$manifest.name = \"$($manifest.name)-sxs\"
$manifest | ConvertTo-Json -depth 100 | Out-File $manifestPath -Encoding utf8NoBOM

原始文件有:

        {
            \"name\": \"vsVersion\",
            \"type\": \"pickList\",
            \"label\": \"Visual Studio Version\",
            \"required\": false,
            \"helpMarkDown\": \"If the preferred version cannot be found, the latest version found will be used instead.\",
            \"defaultValue\": \"latest\",
            \"options\": {
                \"latest\": \"Latest\",
                \"17.0\": \"Visual Studio 2022\",
                \"16.0\": \"Visual Studio 2019\",
                \"15.0\": \"Visual Studio 2017\",
                \"14.0\": \"Visual Studio 2015\",
                \"12.0\": \"Visual Studio 2013\",
                \"11.0\": \"Visual Studio 2012\"
            }
        },

写出的文件有:

    {
      \"required\": false,
      \"type\": \"pickList\",
      \"name\": \"vsVersion\",
      \"options\": {
        \"11.0\": \"Visual Studio 2012\",
        \"12.0\": \"Visual Studio 2013\",
        \"14.0\": \"Visual Studio 2015\",
        \"17.0\": \"Visual Studio 2022\",
        \"15.0\": \"Visual Studio 2017\",
        \"16.0\": \"Visual Studio 2019\",
        \"latest\": \"Latest\"
      },
      \"helpMarkDown\": \"If the preferred version cannot be found, the latest version found will be used instead.\",
      \"label\": \"Visual Studio Version\",
      \"defaultValue\": \"latest\"
    },

有没有办法保留元素的原始顺序?

  • 删除 -AsHashtable 参数开关,哈希表不会按设计保留顺序。
  • 不能,有一些无法加载的重复元素。尝试查看升级 PWSH 是否可行:github.com/PowerShell/PowerShell/issues/…
  • 如果您的源 JSON 描述具有重复属性/键名称的对象,那么两者都无济于事 - PowerShell 将吞下/隐藏重复项并破坏您的 JSON。也许首先与编写 JSON 的任何软件的作者交谈?

标签: json powershell github-actions powershell-core


【解决方案1】:

好的,所以这是最近在v7.3.0-preview.6 中修复的。

我最终将此添加到我的 GitHub Actions 工作流程中,以使用预览版本而不是主版本:

- run: |
    Invoke-Expression "& { $(irm https://aka.ms/install-powershell.ps1) } -UseMSI -preview -quiet"
    "C:\Program Files\PowerShell\7-preview" >> $env:GITHUB_PATH
  name: Upgrade to latest preview of powershell 
  # https://github.com/PowerShell/PowerShell/issues/17404#issuecomment-1188348379

这神奇地解决了我的问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-24
    • 2021-02-03
    • 1970-01-01
    • 2013-12-23
    • 2013-06-03
    相关资源
    最近更新 更多