Skip to content

ConvertTo-Json: unexpected behavior with objects that have ETS properties (NoteProperty, ScriptProperty) #5797

Closed

Description

Instances of types that normally serialize to a JSON scalar (basic JSON data type: string, number, Boolean) should not serialize to objects just because - situationally - NoteProperty and ScriptProperty members may be present - not least because such members may be added automatically by PowerShell.

Additionally, the current behavior is inconsistent, possibly related to #5579.

Also, with a ScriptProperty member present on a [string] instance, ConvertTo-Json crashes as of PowerShell Core v6.1.0-preview.3 - see #7091

Steps to reproduce

[ordered] @{ d1 = [datetime]::now; d2 = get-date  } | ConvertTo-Json

Expected behavior

{
  "d1": "2018-01-05T09:25:37.037783+01:00",
  "d2": "2018-01-05T09:25:37.037783+01:00",
}

Actual behavior

{
  "d1": "2018-01-05T09:25:37.037783+01:00",
  "d2": {
    "value": "2018-01-05T09:25:37.037915+01:00",
    "DisplayHint": 2,
    "DateTime": "Friday, January 5, 2018 9:25:37 AM"
  }
}

Note how the presence of the DisplayHint and DateTime members added by Get-Date caused the value to no longer serialize as a single string, but as an object with said members (yet not any of the type's regular properties).

In some cases, using an intermediate variable makes the problem go away:

$dt = get-date
[ordered] @{ d1 = [datetime]::now; d2 = $dt  } | ConvertTo-Json # OK

That said, with other objects, such as those with provider-added properties, the problem surfaces even with an intermediate variable:

'hi' > t.txt
$s = Get-Content t.txt
$s | ConvertTo-Json   # !! outputs a JSON object with many provider properties

Again, what normally serializes as a string is unexpectedly serialized as an object due to the presence of NoteProperty members.

Finally, when sending an instance with even just a ScriptProperty member through the pipeline, the problem surfaces too:

> [datetime]::now | ConvertTo-Json
{
  "value": "2018-01-07T06:18:29.821274+01:00",
  "DateTime": "Sunday, January 7, 2018 6:18:29 AM"
}

Note that if the instance is nested inside a hashtable / custom object, the problem does not occur, as demonstrated above.
It also doesn't occur if you use -InputObject instead of the pipeline: ConvertTo-Json ([datetime]::now)

Workarounds

Either: apply .psobject.baseobject to the command producing the object to serialize to JSON:

@{ d = (Get-Date).psobject.BaseObject } | ConvertTo-Json

Or: cast to the expected type (or, with an intermediate variable, type-constrain it):

@{ d = [datetime] (Get-Date) } | ConvertTo-Json

Note: The above workarounds only work if the problematic object is not the input object as a whole.

If so, the only workaround I'm aware of is to pass the input object via -InputObject rather than the pipeline:

ConvertTo-Json ([datetime] (Get-Date))   # OK, due to using -InputObject

# !! BROKEN, due to using the pipeline, though, curiously, only
# !! the "DateTime" ScriptProperty shows up, not the "DisplayHint" NoteProperty
[datetime] (Get-Date) | ConvertTo-Json  

Environment data

PowerShell Core v6.0.0-rc.2 (v6.0.0-rc.2) on macOS 10.13.2

Activity

  1. added
    Issue-Discussion
    on Jan 5, 2018
  2. markekraus commented on Jan 5, 2018

    @markekraus
    Contributor

    Michael Klement (@mklement0) I believe this to be by design and desirable. what is undesirable, IMO, is the operation of get-date. I have #5676 to address this. This issue is kind of a duplicate of that.

  3. mklement0 commented on Jan 6, 2018

    @mklement0
    ContributorAuthor

    Mark Kraus (@markekraus): The problem is more generic than that - see my newly added Get-Content example and reworked initial post in general.

    Also note that #5676 doesn't cover the "DateTime" ScriptProperty member.

    I suggest closing #5676 in favor of this one.

  4. changed the title [-]ConvertTo-Json unexpectedly also serializes automatically added NoteProperty and ScriptProperty members[/-] [+]ConvertTo-Json unexpectedly also serializes automatically added NoteProperty and ScriptProperty members, inconsistently[/+] on Jan 6, 2018
  5. markekraus commented on Jan 6, 2018

    @markekraus
    Contributor

    Michael Klement (@mklement0) I just don't think this is possible or desirebale.

    How would ConvertTo-Json know if what it's getting is a wrapped object result from get-date or get-content or a PSObject created by a user that looks like one? That's why I think he fix for this needs to be with each command that does some wrapping. I'll keep my issue open because it applies to more than JSON conversion for dates. but i'm not sure what the approach is for this issue. There is always unexpected behavior around PSObject black magic.

  6. changed the title [-]ConvertTo-Json unexpectedly also serializes automatically added NoteProperty and ScriptProperty members, inconsistently[/-] [+]ConvertTo-Json: unexpected behavior with objects that have NoteProperty / ScriptProperty members[/+] on Jan 7, 2018
  7. mklement0 commented on Jan 7, 2018

    @mklement0
    ContributorAuthor

    Mark Kraus (@markekraus):

    How would ConvertTo-Json know if what it's getting is a wrapped object result from get-date or get-content or a PSObject created by a user that looks like one?

    You're right, that would be tricky, but I've since realized that the problem can be tackled differently, and I've substantially revised the original post; in a nutshell:

    Types that normally serializes to a scalar (a basic JSON data type) should never serialize differently based on the situational presence of NoteProperty / ScriptProperty members.

  8. changed the title [-]ConvertTo-Json: unexpected behavior with objects that have NoteProperty / ScriptProperty members[/-] [+]ConvertTo-Json: unexpected behavior with objects that have NoteProperty members[/+] on Jan 7, 2018
  9. changed the title [-]ConvertTo-Json: unexpected behavior with objects that have NoteProperty members[/-] [+]ConvertTo-Json: unexpected behavior with objects that have ETS properties (NoteProperty, ScriptProperty)[/+] on Jun 17, 2018
  10. msftrncs commented on Mar 12, 2019

    @msftrncs
    Contributor

    I have written up my own ConvertTo-CSON, and in it I use -is [valuetype] to catch objects that would be better as just a scalar value. The get-date example falls under this condition. If the base object is scalar or string, its probably best output as a scalar value. I have also written a PLIST (XML) converter and it worked the same way, as extra object notation in a PLIST would be undesirable.

    Reference: https://github.com/msftrncs/PwshOutCSON

  11. vexx32 commented on Mar 13, 2019

    @vexx32
    Collaborator

    Conceivably we could do something similar. However, ValueType encompasses all structs and may be an unsuitable reference as JSON only has a handful of standard representations.

    We can simply refer to the spec and account for each type that it has a scalar value form for, and treat all others as they are normally treated, I would think?

  12. mklement0 commented on Apr 25, 2019

    @mklement0
    ContributorAuthor

    Agreed, Rain Sallow (/u/ta11ow) (@vexx32).

    Separately, it's worth considering a new ConvertTo-Json switch (-Raw, in line with #7855?) that input-globally opts out of serializing ETS properties (except for [pscustomobject] instances, which are nothing but ETS properties).

  13. 15 remaining items

  14. mklement0 commented on Nov 6, 2020

    @mklement0
    ContributorAuthor

    Let me try to summarize what I think are viable options:

    If backward compatibility is paramount:

    • Option A:
      • Implement ConvertTo-Json -Raw, which is all that is needed:
        • Users can at their discretion opt-out of ETS-property serialization altogether.
        • For control over individual properties, Select-Object can be used.

    If the largely useless serialization of [datetime] and [string] via Get-Content is allowed to change.

    • Option B: Categorically prevent the serialization of ETS properties on those types that become JSON primitives (strings, numbers, Booleans), but provide a way to control ETS property serialization for all other types:

      • Selectively ignore ETS properties for said types.
      • Implement ConvertTo-Json -Raw
    • Option C: Retain the ability to serialize ETS properties on all types, but selectively hide the PowerShell-defined [datetime] and [string] ETS members:

      • To solve the problem at hand, this hiding mechanism could be an internal implementation detail.
      • However - and this is really a separate issue, which I encourage you, Ilya (@iSazonov), to spin out into a separate proposal - we could expose this ability to users as well, as Ilya (@iSazonov) suggested, via Add-Member -Hidden, Update-TypeData, and .types.ps1xml files.

    Separately, there's still the problematic inconsistency in the current serialization behavior with respect to whether a given decorated object is the input object itself or nested inside another object (conversely this means that ConvertTo-Json -Raw should apply to the entire object graph):

    # Add an instance ETS property 'NEWPROP'
    $o = [System.Drawing.Size]::new(1,1) | Add-member -PassThru NEWPROP VALUE
    
    # Serialize it as a whole: instance member is SERIALIZED.
    PS> $o | ConvertTo-Json
    {
      "IsEmpty": false,
      "Width": 1,
      "Height": 1,
      "NEWPROP": "VALUE"
    }
    
    # Serialize it nested inside another object: instance member is IGNORED.
    PS> @{ foo = $o } | ConvertTo-Json
    {
      "foo": {
        "IsEmpty": false,
        "Width": 1,
        "Height": 1
      }
    }
  15. added
    Review - Committee
    on Nov 28, 2020
  16. SteveL-MSFT commented on Dec 16, 2020

    @SteveL-MSFT
    Member

    @PowerShell/powershell-committee reviewed this again, as there is already code within PowerShell to handle ETS properties so we would accept augmentations to that code to special case not serializing [datetime] and [string] ETS properties.

  17. added
    Committee-Reviewed
    and removed
    Review - Committee
    on Dec 16, 2020
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

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions