Search code examples
jsonpowershellroundtrip

Non-broken (round-trip capable) ConvertFrom-Json / ConvertTo-Json in Powershell


PowerShell is unable to reliably round-trip JSON by default. How can I ensure that such JSON is correctly round-tripped?

Here is a minimal example of the broken round-trip serialization:

PS> '{"a":[{"b":{}}]}' | ConvertFrom-Json | ConvertTo-Json -Compress
{"a":[{"b":""}]}

The unexpected change from {} to "" results in JSON which is no longer valid.

This is under version 5.1:

PS> $PSVersionTable.PSVersion.ToString()
5.1.15063.674

Similarly, '[{"b":{}]' | ConvertFrom-Json | ConvertTo-Json is also questionable, as discussed in https://windowsserver.uservoice.com/forums/301869-powershell/suggestions/15123162-convertto-json-doesn-t-serialize-simple-objects-pr. However, consider that questionable nature not covered in this question.


Solution

  • A little bit of PEBKAC, a little bit of Why Is That The Behavior?!

    It seems to be an issue with -Depth and the pruning logic. Setting a "higher depth" results in round-trip behavior working as expected. Having the truncation end as a string, as opposed to say null, seems unfortunate - although possibly consistent if one finds that "To String" is the correct termination.

    Change to "" (unexpected):

    PS> '{"a":[{"b":{}}]}' | ConvertFrom-Json | ConvertTo-Json -Compress -Depth 2
    '{"a":[{"b":""}]}'
    

    Round-trip (expected):

    PS> '{"a":[{"b":{}}]}' | ConvertFrom-Json | ConvertTo-Json -Compress -Depth 3
    '{"a":[{"b":{}}]}'