Home > other >  Removing Objects from JSON using powershell
Removing Objects from JSON using powershell

Time:03-17

i have a test.json file which has below structure:

{
  "name": "test",
  "class": "4",
  "exam": "test",
  "marks": "4"
}

i want to remove some pairs from it like exam and class, nd ultimately it should look like below:

{
  "name": "test",
  "marks": "4"
}

how can i do it from powershell?

CodePudding user response:

Your post was not completely clear if you wanted to remove certain keys, or if you only wanted to retain marks and name. The code below performs the latter:

Get-Content 'test.json' -Raw | 
    ConvertFrom-Json | 
    Select-Object name, marks | 
    ConvertTo-Json

Result:

{
    "name":  "test",
    "marks":  "4"
}

CodePudding user response:

powershell cmd:

PS> $obj = Get-Content .\aaa.json | ConvertFrom-Json
PS> $obj.psobject.properties.remove('exam')
PS> $obj.psobject.properties.remove('class')
PS> $obj | ConvertTo-Json

output:

{
    "name":  "test",
    "marks":  "4"
}
  • Related