首页 > 解决方案 > 如何从我的 JSON 对象中删除条目?

问题描述

# helper to turn PSCustomObject into a list of key/value pairs
function Get-ObjectMembers {
    [CmdletBinding()]
    Param(
        [Parameter(Mandatory=$True, ValueFromPipeline=$True)]
        [PSCustomObject]$obj
    )
    $obj | Get-Member -MemberType NoteProperty | ForEach-Object {
        $key = $_.Name
        [PSCustomObject]@{Key = $key; Value = $obj."$key"}
    }
}

$entry = [PSCustomObject]@{
    PostedDate = "04/18/2018"
    JobTitle = "King"
    Street = "Bloor"
    City = "Toronto"
    DocumentURL = "../path/to/file.pdf"
}



$path = "A:\path\to\file.json"
$entry = Get-Content $path | ConvertFrom-Json

$entry

$today = (Get-Date).ToString('MM/dd/yyyy')#Get-Date -Date -format MM/dd/yyyy
$today = [datetime]::ParseExact($today, "MM/dd/yyyy", [System.Globalization.CultureInfo]::CurrentCulture)

foreach($date in $entry.Closing)
{
    $newdate = Get-Date $date.ToString()
    $newdate = $newdate.ToString('MM/dd/yyyy')
    $newdate = [datetime]::ParseExact($newdate, "MM/dd/yyyy", [System.Globalization.CultureInfo]::CurrentCulture)

    if($today -gt $newdate)
    {
        Write-Host $date
        #remove element from the JSON list
    }
}

我不知道如何从 JSON 对象中删除元素并将已删除项目的副本另存为不同的 JSON 文件

我在 Windows 10 上使用 PowerShell 5.1

标签: jsonfilepowershell

解决方案


“我不知道如何从 JSON 对象中删除元素并将已删除项目的副本另存为不同的 JSON 文件”

你总是可以使用Where-Object

$entry | where { $_.whatever -ne 'something' } | convertto-json | out-file whatever.js

要根据属性删除节点,请尝试以下操作:

$entry.Section.Whatever = $entry.Section.Whatever| Select-Object * -ExcludeProperty Something

要覆盖现有的 JSON 对象,请尝试以下操作:

$entry = $entry | where { $_.whatever -ne 'something' }

推荐阅读