如何从JSON对象中删除条目? [英] How do I remove an entry from my JSON Object?

查看:122
本文介绍了如何从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文件

I can't figure out how I can remove an element from the JSON Object and save a copy of the removed items as a different JSON file

我正在Windows 10上使用PowerShell 5.1

I am using PowerShell 5.1 on Windows 10

推荐答案

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

"I can't figure out how I can remove an element from the JSON Object and save a copy of the removed items as a different JSON file"

您始终可以使用目标对象

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

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

And to remove nodes based on property, try something like this:

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

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

And to over-write the existing JSON object, try something like this:

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

这篇关于如何从JSON对象中删除条目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆