在Powershell7.2中,JSON反序列化为对象的方式在日期方面似乎有了变化->而不是字符串,现在是DateTime.但我希望具有"旧"行为,即将其作为字符串而不是DateTime处理.

在Powershell7.2中使用ConvertFrom-Json时,如何将所有日期反序列化为字符串而不是日期时间?

EDIT:

$val = '{ "date":"2022-09-30T07:04:23.571+00:00" }' | ConvertFrom-Json
$val.date.GetType().FullName

推荐答案

This is actually a known issue, see: #13598 Add a -DateKind parameter to ConvertFrom-Json to control how System.DateTime / System.DateTimeOffset values are constructed. Yet I think there is no easy solution for this. One thing you might do is just invoke (Windows) PowerShell. Which isn't currently straights forward as well therefore I have created a small wrapper to send and receive complex objects between PowerShell sessions (see also my #18460 Invoke-PowerShell purpose):

function Invoke-PowerShell ($Command) {
    $SerializeOutput = @"
         `$Output = $Command
         [System.Management.Automation.PSSerializer]::Serialize(`$Output)
"@
    $Bytes = [System.Text.Encoding]::Unicode.GetBytes($SerializeOutput)
    $EncodedCommand = [Convert]::ToBase64String($Bytes)
    $PSSerial = PowerShell -EncodedCommand $EncodedCommand
    [System.Management.Automation.PSSerializer]::Deserialize($PSSerial)
}

用途:

Invoke-PowerShell { '{ "date":"2022-09-30T07:04:23.571+00:00" }' | ConvertFrom-Json }

date
----
2022-09-30T07:04:23.571+00:00

更新

正如100 comments 的那样,我显然把答案复杂化了.

通过Powershell.exe调用是一种实用的解决方法(尽管速度很慢且仅适用于Windows),但请注意,您不需要帮助器函数:如果将script block传递给Powershell.exe(或pwsh.exe)from PowerShell,则基于Based64 CLIXML的序列化将在后台自动发生:出于这个原因,try powershell.exe -noprofile { $args | ConvertFrom-Json } -args '{ "date":"2022-09-30T07:04:23.571+00:00" }',我认为没有必要使用Invoke-PowerShell cmdlet.

$Json = '{ "date":"2022-09-30T07:04:23.571+00:00" }'
powershell.exe -noprofile { $args | ConvertFrom-Json } -args $Json

date
----
2022-09-30T07:04:23.571+00:00

Json相关问答推荐

Google Page to JSON应用程序脚本出现CORS错误

PowerShell脚本-替换json数组(转义$var将被视为不带双引号的文本)

Bash和echo命令出现意外结果

盒子图显示不正确

如何在我的响应模型中修复此问题:[期望的值类型为';Map<;Dynamic,Dynamic&>;,但获得的值类型为';NULL&39;]

交换键和数组值,将旧键转换为新数组值,使用 jq

在Databricks中如何将JSON文件作为字典读取

每次在 SoapUI 中发送请求时,将 JSON 响应的子 node 分配给项目变量

如何使用nifi从json文件中过滤属性

使用带有逗号的字段名称构建 struct

使用 SwiftUI 在 API 调用中解码嵌套 JSON 响应时遇到问题

在 Perl Mojolicious 中呈现 JSON 时防止转义字符

在 C# 中解析 Json rest api 响应

在 Http Header 中使用 Json 字符串

读取 HttpwebResponse json 响应,C#

IE10/11 Ajax XHR 错误 - SCRIPT7002:XMLHttpRequest:网络错误 0x2ef3

如何对 jq 中的 map 数组中的值求和?

将多个值存储在json中的单个键中

如何从 github API 解析链接头

如何对 Javascript 对象进行排序,或将其转换为数组?