Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to round-trip this JSON to PSObject and back in Powershell

Powershell can't seem to correctly round-trip this JSON object:

{
    "settings": {
        "minimumApproverCount": 2,
        "creatorVoteCounts": false,
        "scope": [
            {
                "refName": "refs/heads/d14rel",
                "matchKind": "Exact",
                "repositoryId": "a290117c-5a8a-40f7-bc2c-f14dbe3acf6d"
            }
        ]
    }
}

Assuming $json is a string, this command:

$json | ConvertFrom-Json | ConvertTo-Json

produces the wrong JSON out of it:

{
    "settings":  {
                     "minimumApproverCount":  2,
                     "creatorVoteCounts":  false,
                     "scope":  [
                                   "@{refName=refs/heads/d14rel; matchKind=Exact; repositoryId=a290117c-5a8a-40f7-bc2c-f14db
e3acf6d}"
                               ]
                 }
}

Notice it gets the "scope" variable wrong. Is there a way to fix this?

like image 761
Andrew Arnott Avatar asked Sep 25 '15 04:09

Andrew Arnott


People also ask

Can PowerShell parse JSON?

PowerShell makes it easy to modify JSON by converting JSON to a PSCustomObject. The object can then be modified easily like any other object. The object can then be exported back out using ConvertTo-Json.

What does ConvertFrom-JSON do?

The ConvertFrom-Json cmdlet converts a JavaScript Object Notation (JSON) formatted string to a custom PSCustomObject object that has a property for each field in the JSON string. JSON is commonly used by web sites to provide a textual representation of objects.


1 Answers

Use the parameter Depth with value 3 or larger. The default 2 is not enough, deeper data are simply converted to strings.

$json | ConvertFrom-Json | ConvertTo-Json -Depth 3

Output

{
    "settings":  {
                     "minimumApproverCount":  2,
                     "creatorVoteCounts":  false,
                     "scope":  [
                                   {
                                       "refName":  "refs/heads/d14rel",
                                       "matchKind":  "Exact",
                                       "repositoryId":  "a290117c-5a8a-40f7-bc2c-f14dbe3acf6d"
                                   }
                               ]
                 }
}
like image 80
Roman Kuzmin Avatar answered Oct 07 '22 15:10

Roman Kuzmin