Repository navigation
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-JsonExpected 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 # OKThat 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 propertiesAgain, 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-JsonOr: cast to the expected type (or, with an intermediate variable, type-constrain it):
@{ d = [datetime] (Get-Date) } | ConvertTo-JsonNote: 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
markekraus commentedon Jan 5, 2018
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.mklement0 commentedon Jan 6, 2018
Mark Kraus (@markekraus): The problem is more generic than that - see my newly added
Get-Contentexample 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.
[-]ConvertTo-Json unexpectedly also serializes automatically added NoteProperty and ScriptProperty members[/-][+]ConvertTo-Json unexpectedly also serializes automatically added NoteProperty and ScriptProperty members, inconsistently[/+]markekraus commentedon Jan 6, 2018
Michael Klement (@mklement0) I just don't think this is possible or desirebale.
How would
ConvertTo-Jsonknow if what it's getting is a wrapped object result fromget-dateorget-contentor 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.[-]ConvertTo-Json unexpectedly also serializes automatically added NoteProperty and ScriptProperty members, inconsistently[/-][+]ConvertTo-Json: unexpected behavior with objects that have NoteProperty / ScriptProperty members[/+]mklement0 commentedon Jan 7, 2018
Mark Kraus (@markekraus):
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.
[-]ConvertTo-Json: unexpected behavior with objects that have NoteProperty / ScriptProperty members[/-][+]ConvertTo-Json: unexpected behavior with objects that have NoteProperty members[/+][-]ConvertTo-Json: unexpected behavior with objects that have NoteProperty members[/-][+]ConvertTo-Json: unexpected behavior with objects that have ETS properties (NoteProperty, ScriptProperty)[/+]msftrncs commentedon Mar 12, 2019
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. Theget-dateexample 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
vexx32 commentedon Mar 13, 2019
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?
mklement0 commentedon Apr 25, 2019
Agreed, Rain Sallow (/u/ta11ow) (@vexx32).
Separately, it's worth considering a new
ConvertTo-Jsonswitch (-Raw, in line with #7855?) that input-globally opts out of serializing ETS properties (except for[pscustomobject]instances, which are nothing but ETS properties).15 remaining items
mklement0 commentedon Nov 6, 2020
Let me try to summarize what I think are viable options:
If backward compatibility is paramount:
ConvertTo-Json -Raw, which is all that is needed:Select-Objectcan be used.If the largely useless serialization of
[datetime]and[string]viaGet-Contentis 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:
ConvertTo-Json -RawOption C: Retain the ability to serialize ETS properties on all types, but selectively hide the PowerShell-defined
[datetime]and[string]ETS members:Add-Member -Hidden,Update-TypeData, and.types.ps1xmlfiles.hiddenmember qualifier for custom PS classes is currently not respected byConvertTo-Json: see Class hidden properties still serialized to JSON #9847Separately, 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 -Rawshould apply to the entire object graph):SteveL-MSFT commentedon Dec 16, 2020
@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.Cast explicitly to string to handle this bug still present in PowerSh…