1

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
}
2
  • 3
    Hash tables are not ordered by default. Use the [ordered] attribute to use a OrderedDictionary instead. Commented Oct 5, 2021 at 13:03
  • 1
    What @AdminOfThings said. Or cast the inner items to [pscustomobject] (will also retain syntactic order) Commented Oct 5, 2021 at 13:04

1 Answer 1

2

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
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.