0
{
    "logs":  [
                 {
                     "timestamp":  "20181216T14:36:12",
                     "description":  "IP connectivity via interface ipmp1 has become degraded.",
                     "type":  "alert",
                     "uuid":  "1234567",
                     "severity":  "Minor"
                 },
                 {
                     "timestamp":  "20181216T14:38:16",
                     "description":  "Network connectivity via port ibp4 has been established.",
                     "type":  "alert",
                     "uuid":  "12345678",
                     "severity":  "Minor"
                 }
             ]
}

我有这个 JSON 对象,我想遍历每个对象并将时间戳更新为更易读的日期。现在,我有

$currentLogs.logs |
Where{$_.type -eq 'alert'} |
ForEach{$_.timestamp = {[datetime]::parseexact($_.timestamp, 'yyyyMMdd\THH:mm:ss', $null)}}

但是当我读取对象 $currentLogs 时,它仍然没有更新。

4

2 回答 2

1

您需要首先解析您的日期/时间,然后应用您想要的格式。如果您不应用任何格式,则该timestamp属性将是一个datetime对象类型,并且转换回 JSON 将对它进行奇怪的格式设置。最好将您的新格式设置为字符串,这样它就不会被 JSON 序列化操作:

$currentLogs.logs | Where type -eq 'alert' | ForEach-Object {
    $_.timestamp = [datetime]::parseexact($_.timestamp, 'yyyyMMddTHH:mm:ss', $null).ToString('yyyy-MM-dd HH:mm:ss')
}

在您的尝试中,您使用了以下代码:

{[datetime]::parseexact($_.timestamp, 'yyyyMMdd\THH:mm:ss', $null)}

使用环绕{}表示脚本块。如果没有调用或调用该脚本块,它只会逐字输出其内容。您可以在控制台中运行上述代码并查看结果。

您也没有datetime在解析尝试后格式化您的对象。默认情况下,ToString()datetime值设置为属性时,控制台中的输出将隐式应用,但隐式格式不会转换为您的 JSON 转换(无论出于何种原因)。

于 2021-07-30T20:23:53.410 回答
0

感谢您显示所需的格式。

要更新 'type' 等于 'alert' 的那些元素,您可以这样做:

$json = @'
{
    "logs":  [
                 {
                     "timestamp":  "20181216T14:36:12",
                     "description":  "IP connectivity via interface ipmp1 has become degraded.",
                     "type":  "alert",
                     "uuid":  "1234567",
                     "severity":  "Minor"
                 },
                 {
                     "timestamp":  "20181216T14:38:16",
                     "description":  "Network connectivity via port ibp4 has been established.",
                     "type":  "alert",
                     "uuid":  "12345678",
                     "severity":  "Minor"
                 }
             ]
}
'@ | ConvertFrom-Json

# find the objects with 'type' equals 'alert'
$json.logs | Where-Object { $_.type -eq 'alert' } | ForEach-Object { 
    # parse the date in its current format
    $date = [datetime]::ParseExact($_.timestamp, 'yyyyMMddTHH:mm:ss', $null)
    # and write back with the new format
    $_.timestamp = '{0:yyyy-MM-dd HH:mm:ss}' -f $date
}

# convert back to json
$json | ConvertTo-Json

如果您想保存到文件,请在上面的最后一行附加| Set-Content -Path 'X:\Path\To\Updated.json'

于 2021-08-02T14:53:14.820 回答