简体   繁体   English

解析 json 并将其写回时保持元素的顺序

[英]Keep order of elements when parsing json and writing it back out

I'm reading in a json file.我正在阅读 json 文件。 Updating a few values and writing it back out.更新一些值并将其写回。 Some elements end up out-of-order.有些元素最终会出现乱序。

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

The original file had:原始文件有:

        {
            "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"
            }
        },

The written out file has:写出的文件有:

    {
      "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"
    },

Is there a way to retain the original order of elements?有没有办法保留元素的原始顺序?

Ok, so this was REALLY recently fixed in v7.3.0-preview.6 .好的,所以这确实是最近在v7.3.0-preview.6中修复的。

I ended up adding this to my GitHub Actions workflow to use the preview version instead of the main version:我最终将此添加到我的 GitHub 操作工作流程中,以使用预览版本而不是主版本:

- 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 powerhshell 
  # https://github.com/PowerShell/PowerShell/issues/17404#issuecomment-1188348379

This magically fixes my problems.这神奇地解决了我的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM