Home > database >  Convert a Powershell-Object to JSON with sorting
Convert a Powershell-Object to JSON with sorting

Time:10-06

I have a PSCustomObject in Powershell which I want to convert to JSON. The Key-Value-Pair should be under the "children" array. Can you help?

Powershell:

#PowershellObject
$BookmarkContainer = [PSCustomObject]@{
    "roots" = @{
        "other" = @{
            "children" = @()
        }
        "bookmark_bar" = @{
            "children" = @()
            "name" ="FavouriteBar"
            "type" ="folder"
            
        }
    }
    "version"=1
}

JSON-Output:

{
    "roots":  {
        "bookmark_bar":  {
            "name":  "FavouriteBar",
            "type":  "folder",
            "children":  [ ]
        },
        "other":  {
            "children":  [ ]
        }
    },
    "version":  1
}

Intended output:

{
    "roots":  {
        "bookmark_bar":  {
            "children":  [ ],
            "name":  "FavouriteBar",
            "type":  "folder"
        },
        "other":  {
            "children":  [ ]
        }
    },
    "version":  1
}

CodePudding user response:

Hash tables are not ordered by default. Use the [ordered] attribute to use a OrderedDictionary instead. Use the -Depth parameter on ConvertTo-Json since its default value is 2 and you have more than 2 levels of nesting.

$BookmarkContainer = [PSCustomObject]@{
    "roots" = [ordered]@{
        "other" = @{
            "children" = @()
        }
        "bookmark_bar" = [ordered]@{
            "children" = @()
            "name" ="FavouriteBar"
            "type" ="folder"
            
        }
    }
    "version"=1
}

$BookmarkContainer | ConvertTo-Json -Depth 4

Output:

{
    "roots":  {
                  "other":  {
                                "children":  [

                                             ]
                            },
                  "bookmark_bar":  {
                                       "children":  [

                                                    ],
                                       "name":  "FavouriteBar",
                                       "type":  "folder"
                                   }
              },
    "version":  1
}
  • Related