Skip to content

Consider removing the default -Depth value from ConvertTo-Json #8393

Closed

Description

Summary of the proposal:

Motivation

-Depth defaulting to 2 in ConvertTo-Json has caused much confusion and frustration over the years; iRon7 has recently tried to create a "canonical" post on SO, which also shows how frequently the issue is arising.

Currently, an input object tree that exceeds the (default) depth doesn't cause an error, but results in near-useless .psobject.ToString() serialization of property values that exceed the depth (see #8381 for a proposal to visualize the cut-off differently).

In combination with the low default -Depth value of 2, that makes for frequent user frustration, because the behavior frequently amounts to quiet de-facto failure that may not be discovered until later.

The seemingly arbitrary and quiet truncation is surprising to most users, and having to account for it in every ConvertTo-Json call is an unnecessary burden.

Backward-compatibility impact

The only way in which I think existing code could be impacted is in that payloads generated with ConvertTo-Json could now increase in depth (and size), if users previously relied on the implicit cut-off at depth 2 - that strikes me as a Bucket 3: Unlikely Grey Area change.

Activity

  1. added
    Issue-Discussion
    on Dec 4, 2018
  2. iSazonov commented on Dec 4, 2018

    @iSazonov
    Collaborator
  3. iRon7 commented on Dec 4, 2018

    @iRon7

    Michael Klement (@mklement0), thank for picking this up.
    It is not completely clear to me what happens with the circular references.

    • If you leave them intact up till the hard-coded internal limit of 100, then your Backward-compatibility impact might be even higher than expected: Take for example: get-service | Where-Object {$_.DisplayName -match 'tcp/ip*'} | ConvertTo-Json -Depth 10 where it just concerns a single object (and not even all services) with a depth of 10. Knowing that a depth of 10 for this command takes already several seconds and produces a file of 22Mb (and for -Depth 12; 40sec/ 160Mb).

    • At the other hand, if you cut them off at the point where the circular reference is detected, users might lose circular properties (e.g. $Object.parent.parent.parent.parent). Which might be a downwards compatibility concern too if the property is within the originally used depth (2).

    Maybe an new (user) parameter something like: -RecurringDepth = 2 (default: 2), in addition to your purpose might help. In this idea, the -RecurringDepth will cut off only recurring references at the given depth (or below).
    But would also understand if additional parameters are generally unwanted.

  4. SteveL-MSFT commented on Dec 4, 2018

    @SteveL-MSFT
    Member

    iRon7 I don't know the history of -Depth 2, but I also suspect it has to do with recursion where .NET objects reference other instances. The obvious case as you noted is with services which have DependentServices and ServicesDependedOn creating circular references. A -RecurringDepth parameter seems like a reasonable solution along with a warning if the depth gets hit. New parameters are fine as long as they make sense and generally help avoid a breaking change.

  5. mklement0 commented on Dec 4, 2018

    @mklement0
    ContributorAuthor

    iRon7:

    I see the problem with the depth of 100, but my guess is that it's fine to lower this to a more reasonable number that covers the majority of use cases while preventing infinite recursion.
    (Again, only people with excessively deep trees who rely on default truncation at depth 2 would be affected, which doesn't strike me as likely.)

    As for circular references and the default value preventing "runaway" strings when serializing arbitrary .NET types:
    It doesn't really make sense to use ConvertTo-Json for that - use Export-CliXml instead.
    So I'm not sure that -RecurringDepth is needed, but, as Steve Lee (@SteveL-MSFT) says, adding parameters is an option.

    However, the gist of my proposal is to bring sane default behavior to ConvertTo-Json, and that won't be possible without what is technically a breaking change - fingers crossed for bucket 3, though.

    The typical use case is to use custom-made data-transfer objects ("property bags"; hashtables or custom objects) that you want serialized in full - the internal hard limit is there as a safety belt.

    Cutting off the input object tree at a given depth should always be an explicit decision, not quietly applied default behavior that may initially even go unnoticed.

    That concerns about incautious, atypical use dictate default behavior that:

    • defies user expectations to begin with,
    • is a challenge to remember,
    • is a nuisance to work around, because you need to figure out the actual depth of your data and keep the parameter in sync with later changes (unless you go for -Depth 100, which shouldn't be necessary)

    has led to longstanding frustration with the cmdlet.

  6. SteveL-MSFT commented on Dec 5, 2018

    @SteveL-MSFT
    Member

    Michael Klement (@mklement0) assuming your assertion on use case is correct, it would be possible to treat PSCustomObject and HashTables differently from other .NET types, but then we have asymmetric behavior and could be confusing to some users.

    It would be great if someone could script out some tests to see if other types besides Service has circular references. If that is the case, it may make more sense to special case that one (maybe output a warning) and increase the depth by default.

  7. mklement0 commented on Dec 6, 2018

    @mklement0
    ContributorAuthor

    Steve Lee (@SteveL-MSFT):

    As for what use cases are typical:

    My observations are based on what I came across on Stack Overflow and what makes sense to me, but you could use your Twitter clout to solicit feedback from a wider audience.

    On a similar note, iRon7: If you support this proposal at least in essence, please update your SO self-answer to point to my answer, which promotes this proposal. With the current vote tally, users are likely to focus on your justification of the status quo.

  8. mklement0 commented on Dec 6, 2018

    @mklement0
    ContributorAuthor

    As for treating [hashtable] and [pscustomobject] instances differently:

    Yes, that could be confusing, so we should avoid it. That said, if too much legacy code turns out to rely on the implicit -Depth 2 truncation, it may be an option, though.

    It would be great if someone could script out some tests to see if other types besides Service has circular references.

    Given that it generally makes no sense to blindly use ConvertTo-Json with arbitrary .NET types, I wouldn't be too concerned about that - except with respect to legacy code in order to assess whether the -Depth 2 should be retained selectively for non-hashtable-non-custom-object instances.

    Here are the ca. 20,000 hits for PowerShell code that calls ConvertTo-Json on GitHub:

    https://github.com/search?p=5&q=language%3Apowershell+ConvertTo-Json&type=Code

  9. markekraus commented on Dec 7, 2018

    @markekraus
    Contributor

    I have long suspected the default Depth was too low. That was until I experimented with setting the Depth to 100 in $PSDefaultParameterValues. The result was a marked increase in execution times for bunch of automation I was responsible for. In some cases, the scripts would execute indefinitely. Large numbers of deep and wide (and sometimes infinitely deep) objects can account for that. Changing this could result in user complaints that scripts are taking longer after upgrading to a pwsh version where the depth was set too high. In some cases, they may even have scripts that never finish executing.

    While I definitely feel the pain of the default depth being low and silently truncating, I disagree with the assertion that this would not be an impactful change.

    I think the default behavior from the beginning should have been to error instead of silently truncate. I agree that 2 is too low. I disagree that increasing the default to 100 is a good idea.

    As was discussed in another issue or PR, there are 2 concepts at play here: depth and action when that depth is reached. I think for most uses, slightly increasing the default depth and changing the default behavior to error would be sufficient is solving the majority of pain points. This would need to come with the ability to truncate as an option, as without it infinitely deep objects could never be serialized.

    I believe that the assertion that users rarely serialize arbitrary .NET types is false. I have seen plenty of logging that lazily throws any and all objects through ConvertTo-Json -Compress. I would caution that this assertion be investigated thoroughly before any decisions are made.

  10. mklement0 commented on Dec 10, 2018

    @mklement0
    ContributorAuthor

    I have seen plenty of logging that lazily throws any and all objects through ConvertTo-Json -Compress

    Yeah, looking at some of the code here on GitHub seems to confirm the unfortunate reality of lazy ConvertTo-Json use being not uncommon.

    In light of this, Steve Lee (@SteveL-MSFT)'s suggestion is well worth considering; to flesh it out some more:

    • If an input object is a deliberately constructed DTO (property bag), do not apply the default depth (let the internal max. depth prevent infinite recursion); specifically, this applies to:

      • Hashtables and ordered hashtables
      • [pscustomobject] instances whose .pstypenames array contains only System.Management.Automation.PSCustomObject and System.Object (to rule out arbitrary deserialized .NET types)
      • Classes created with PowerShell's class construct.
      • Treat the entries / properties of these two types as follows:
        • Serialize primitive .NET types as usual ([string], [bool], [int], ...)
        • Recurse on entries / properties of the same type (nested hashtable / custom object), applying only the overall max. depth)
        • Serialize any other types with hard-coded per-object depth 1 - that is, serialize only the immediate properties of such a type, and represent nested objects as they .ToString() values.
          • In general, assume that all properties that matter in the resulting JSON should be spelled out via hashtable / [pscustomobject] instances (ultimately) containing properties that have scalar JSON representations - i.e., deliberately constructed as DTOs.
          • The hard-coded per-object depth of 1 ensures that old code that wrapped arbitrary .NET types in hashtables / custom objects continues to work as before (e.g.,
            @{ foo = Get-Item / } | ConvertTo-Json)
    • With any other input, retain the current behavior.

    This would alleviate the pain based on straightforward exception rules (the inevitable price to pay for remaining mostly backward-compatible):

    • Lazy piping of arbitrary .NET types to ConvertTo-Json would work as before.

    • Deliberately constructed DTOs would no longer be subject to the quiet truncation at depth 2.

  11. markekraus commented on Dec 10, 2018

    @markekraus
    Contributor

    Michael Klement (@mklement0) How would you handle mixed scenarios? For example, depth 1-5 is occupied by property bags, 6 has a .NET Type but 8-11 are property bags again (possible due to ETS)?

  12. mklement0 commented on Dec 10, 2018

    @mklement0
    ContributorAuthor

    Mark Kraus (@markekraus): What I'm proposing amounts to 3 distinct scenarios:

    • If -Depth is present, the behavior will be as it is now, irrespective of the type of input object (quiet truncation at specified depth).

    • Otherwise, in the absence of -Depth:

      • If an object is a DTO, as described above:

        • No overall -Depth value is implied; only the internal max. depth is in effect (which can be increased with an explicit -Depth argument).
        • On a per-nested-non-DTO basis, a fixed, non-configurable depth of 1 is applied (note that if it weren't for backward compatibility, it might be better to use 0, i.e., to only include the immediate properties).
      • If an object is of any other type, the behavior will be as it is now (default depth 2).

    To put it differently: in the absence of -Depth, it is the root of a given input object's tree that selects one of two fundamental behaviors:

    • A DTO root is not limited depth-wise (except by the max. depth), except for nested non-DTOs, if any, which themselves are limited to depth 1.
    • A non-DTO root is limited to overall depth 2, as before.

    Note that I've updated the definition of DTO in the previous comment to include classes created with PowerShell's class construct.

    As for the presence of ETS properties: only the base object's type should govern the behavior.

  13. markekraus commented on Dec 10, 2018

    @markekraus
    Contributor

    I think that proposal of silent asymmetrical behavior will cause more problems than it will solve.

    I really do think there is no decent solution to this that does not involve both a depth parameter and an action to be taken at that depth. I also agree that the default depth could be increased.

  14. mklement0 commented on Dec 11, 2018

    @mklement0
    ContributorAuthor

    Mark Kraus (@markekraus):

    I also agree that the default depth could be increased.

    Given that lazy to-JSON conversion isn't uncommon, that's not really an option, if you want to avoid "marked increase in execution times", as you've stated.
    Attempting a lukewarm compromise along the lines of increasing the default depth to say, 4, is not worth the effort, in my estimation: it can still substantially increase the runtime/memory requirements of lazy conversions while still running the risk of unexpected silent truncation for purposefully constructed DTOs.

    I think that proposal of silent asymmetrical behavior will cause more problems than it will solve.

    Let's start with the problems that it does solve or avoids:

    Deliberately constructed DTOs will serialize as expected - with no depth restriction other than the "safety belt" of 100 levels (which you'll be able to override with -Depth).
    This will remove the major pain point of the current behavior.

    Backward-compatibility:

    • Old code with explicit -Depth will continue to work as-is.
    • Old code that lazily serializes non-DTOs without -Depth will continue to work as-is.
    • The only old code potentially affected is one with explicitly constructed DTOs that relied on implicit truncation at level 2, which strikes me as unlikely.

    Which problems do you think it will cause?

  15. 25 remaining items

  16. SteveL-MSFT commented on Aug 5, 2020

    @SteveL-MSFT
    Member

    @PowerShell/powershell-committee for review, the basic problem is that the default -depth 2 value can end up with "data truncation" where the user is not aware they no longer have full fidelity of the original object. For 7.1, I suggest we add a warning message when the depth is hit. The DTO vs .NET object serialization I think needs more discussion. The asymmetric behavior, by default, may be confusing vs introducing a new switch/parameter to make it opt-in.

  17. SteveL-MSFT commented on Aug 5, 2020

    @SteveL-MSFT
    Member

    @PowerShell/powershell-committee discussed this, we agreed for 7.1, we should emit a warning message when the depth is hit to inform the user that the object has been truncated.

    For additional enhancements, we should explore those as part of Ilya (@iSazonov) changes to move to .NET JSON APIs as an experimental feature.

  18. added
    Committee-Reviewed
    and removed
    Review - Committee
    on Aug 5, 2020
  19. mklement0 commented on Aug 12, 2020

    @mklement0
    ContributorAuthor

    Steve Lee (@SteveL-MSFT)

    The DTO vs .NET object serialization I think needs more discussion. The asymmetric behavior, by default, may be confusing vs introducing a new switch/parameter to make it opt-in.

    Let me point out again that the same asymmetry (DTOs serialized with full depth, others cut off at a given depth) is built into PowerShell's serialization infrastructure.

    The asymmetry makes sense: limiting the depth is only necessary to prevent "runaway serialization" with non-DTOs.

    I've never heard anyone complain about it in the context of serialization, and I suspect the average PowerShell user is unaware of it - despite the fact that loss of information is commonplace (though typically doesn't matter in practice), and the depth (1) is not configurable.

    The asymmetry equally makes sense for ConvertTo-Json, and is even more innocuous there:

    • A deliberately constructed DTO as input you'd by definition want to serialize completely, whatever its depth. This is the primary use case for ConvertTo-Json.

      • While a warning would be a slight improvement over the current behavior, it is still an extraordinarily cumbersome solution, given that it should "just work".
    • Using ConvertTo-Json with arbitrary .NET types such as System.IO.FileInfo is virtually pointless anyway, but should you attempt it, the depth limit would save you from "runaway serialization" (a warning could be issued).

  20. heilkn commented on Aug 14, 2020

    @heilkn

    Hello,

    I would also like to up-vote this issue. Please remove this unexpected behavior. Day to day it costs developers several hours or days to find out the reason for the bugs caused by this.

    I would have even preferred my program to die with an error instead of silently messing with the data structure.

    Kind regards

    Konstantin

  21. 0009-0009-1013-986X commented on Mar 11, 2024

    @0009-0009-1013-986X

    #8393 (comment)

    #13692 (comment) doesn't address this. As https://stackoverflow.com/questions/53583677/unexpected-convertto-json-results-answer-it-has-a-default-depth-of-2#comment94031210_53583678 explains:

    Since circular dependencies are not supported in JSON, writing a serializer that does not support circular dependencies seems the more natural choice over one that only walks to a certain depth. All major JSON serializers other than the one in PowerShell do this. I'd call it a "poor design decision".

    Why should I need to know the depth of the JSON object to be returned before its returned? What if the JSON is of afore-unknown depth? Must I constantly recall it, increasing the depth parameter until I've no error any more? That seems absurd considering the amount of data that might require requesting for large datasets.

    Stack Overflow
    Why do I get unexpected ConvertTo-Json results, why do I get values like System.Collections.Hashtable and/or why does a round-trip ($Json | ConvertFrom-Json | ConvertTo-Json) fail? Meta issue
  22. iRon7 commented on Mar 12, 2024

    @iRon7

    @RokeJulianLockhart,

    The point is that you start of with a PowerShell object (which is based on .Net objects) that in fact does support circular references. As pointed out in the Unexpected ConvertTo-Json results? Answer: it has a default -Depth of 2 example, a property might reference the parent or a grand parent higher up. This might create a circular reference that might go forever:

    $Test = @{Depth = 0}
    $Test.Parent = $Test
    $Test | ConvertTo-Json

    But it might also (dynamically) end somewhere very deep (if I add e.g. a failsafe myself in the concerned object):

    $Test = @{Depth = 0}
    $Test | Add-Member -MemberType 'ScriptProperty' -Name 'Parent' -Value { if ($Test.Depth++ -lt 10) { $Test } }
    $Test | ConvertTo-Json
    
    WARNING: Resulting JSON is truncated as serialization has exceeded the set depth of 2.
    {
      "Depth": 0,
      "Parent": {
        "Depth": 1,
        "Parent": {
          "Depth": 2,
          "Parent": {
            "value": "System.Collections.Hashtable",
            "Parent": {
              "value": "System.Collections.Hashtable",
              "Parent": {
                "value": "System.Collections.Hashtable",
                "Parent": {
                  "value": "System.Collections.Hashtable",
                  "Parent": {
                    "value": "System.Collections.Hashtable",
                    "Parent": {
                      "value": "System.Collections.Hashtable",
                      "Parent": {
                        "value": "System.Collections.Hashtable",
                        "Parent": {
                          "value": "System.Collections.Hashtable",
                          "Parent": null
                        }
                      }
                    }
                  }
                }
              }
            }
          }
        }
      }
    }

    There is indeed no easy way to tell upfront where it ends because:

    • the loop might span any (close to infinitive) number of unique items, and
    • after a certain number of loops it might suddenly bail out (or not at all).

    In other words, "writing a serializer that does not support circular dependencies" is to my opinion not a matter of choice for circular (PowerShell/.Net) objects, the issue is that serializers (by design) lack the possibility to define a circular reference for these type of objects.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

Committee-ReviewedIssue-DiscussionResolution-FixedWG-Cmdlets

Type

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions