Lazy Diary @ Hatena Blog

PowerShell / Java / miscellaneous things about software development, Tips & Gochas. CC BY-SA 4.0/Apache License 2.0

Convert deeply nested hash or array to JSON with ConvertTo-Json

Context

You can read a JSON file like below with ConvertFrom-Json, and write with ConvertTo-Json properly.

PS > Get-Content ./foo.json
{
  "outerHash": {
    "innerHash": {
      "key": "value"
    }
  }
}
PS > Get-Content ./foo.json | ConvertFrom-Json | ConvertTo-Json
{
  "outerHash": {
    "innerHash": {
      "key": "value"
    }
  }
}

Problem

You also can read a JSON file like below with ConvertFrom-Json, but cannot write with ConvertTo-Json properly. ConvertTo-Json write a hash in array in hash as "@{key=value}" style string.

PS > Get-Content ./bar.json
{
  "outerHash": {
    "arrayInHash": [
      {
        "key": "value"
      }
    ]
  }
}
PS > Get-Content ./bar.json | ConvertFrom-Json | ConvertTo-Json
{
  "outerHash": {
    "arrayInHash": [
      "@{key=value}"
    ]
  }
}

In this example, the result of ConvertTo-Json should be identical the result of Get-Content ./bar.json.

Reason

ConvertTo-Json has a option -Depth, and its default value is 2. This option is used when convert nested object to JSON.

Solution

Pass the appropriate value to -Depth option according to your object graph.

PS > Get-Content ./bar.json | ConvertFrom-Json | ConvertTo-Json -Depth 3
{
  "outerHash": {
    "arrayInHash": [
      {
        "key": "value"
      }
    ]
  }
}