Home > database >  Keep order of elements when parsing json and writing it back out
Keep order of elements when parsing json and writing it back out

Time:08-20

I'm reading in a json file. 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?

CodePudding user response:

Ok, so this was REALLY recently fixed in 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:

- 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

This magically fixes my problems.

  • Related