如何从JSON对象中删除条目?

时间:2018-05-09 17:02:25

标签: json file powershell

# 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

2 个答案:

答案 0 :(得分:1)

  

“我无法弄清楚如何从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' }

答案 1 :(得分:1)

如果我们看一下我们的 JSon 对象 $Entry,它看起来像这样:

PostedDate  : 04/18/2018
JobTitle    : King
Street      : Bloor
City        : Toronto
DocumentURL : ../path/to/file.pdf

在 Powershell 中,JSon 对象是一个 PSCustomObject:

$Entry.gettype().fullName
System.Management.Automation.PSCustomObject

所以我们可以像这样删除选定的对象元素:

$entry.PSObject.Properties.Remove("NameOfElementWeWantToRemove")

所以在“PostedDate”的情况下,看起来像这样:

$entry.psobject.properties.remove("PostedDate")

现在 $entry 对象看起来像这样:

JobTitle    : King
Street      : Bloor
City        : Toronto
DocumentURL : ../path/to/file.pdf

并且“PostedDate”已被删除。

所以它真的是一个简单的单衬,

玩得开心!