[英]Non-broken (round-trip capable) ConvertFrom-Json / ConvertTo-Json in Powershell
PowerShell is unable to reliably round-trip JSON by default.默认情况下,PowerShell 无法可靠地往返 JSON。 How can I ensure that such JSON is correctly round-tripped?
我怎样才能确保这种JSON正确往返式操作?
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.从
{}
到""
的意外更改导致 JSON 不再有效。
This is under version 5.1:这是在 5.1 版本下:
PS> $PSVersionTable.PSVersion.ToString()
5.1.15063.674
Similarly, '[{"b":{}]' | ConvertFrom-Json | ConvertTo-Json
同样,
'[{"b":{}]' | ConvertFrom-Json | ConvertTo-Json
'[{"b":{}]' | ConvertFrom-Json | ConvertTo-Json
'[{"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 . '[{"b":{}]' | ConvertFrom-Json | ConvertTo-Json
也有问题,如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.但是,请考虑此问题中未涵盖的可疑性质。
A little bit of PEBKAC, a little bit of Why Is That The Behavior?!一点点PEBKAC,一点点为什么那是行为?!
It seems to be an issue with -Depth
and the pruning logic.这似乎是
-Depth
和修剪逻辑的问题。 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.将截断结束为字符串,而不是说
null
,似乎很不幸——尽管如果发现“To String”是正确的终止,则可能是一致的。
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":{}}]}'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.