Eliminate item from collection of objects in Json using Powershell

I have a scenario where I am importing JSON data into Powershell to update certain values, but I also need to remove specific objects from the imported data.

Here is my import code:

$fileJson = Get-Content -path/Template.json  -Encoding UTF8

In the JSON data, there is an array of objects structured like this:

{
 "resources": [
   {
     "name": "name1"
     "type": "type1"
     "....": "....."
   }, 
   {
     "name": "name2"
     "type": "type2"
     "....": "....."
   },
   {
     "name": "name3"
     "type": "type1"
     "....": "....."
   }
 ]
}

I need to be able to remove a specific object from this array based on a condition. For example, I want to remove the object where "type" equals "type2".

So far, I have tried using .Replace method but it only allows me to replace individual values and not entire objects. Is there a way to delete or skip an entire object based on a condition?

Answer №1

Transform the JSON into a personalized object:

$jsonData = Get-Content -path/Template.json  -Encoding UTF8
$customObject = $jsonData |ConvertFrom-Json 

Utilize Where-Object to refine the resources array:

$customObject.resources = @($customObject.resources |Where-Object type -ne type2)

Revert the modified object back to JSON format and save it to disk:

$customObject |ConvertTo-Json |Set-Content ./path/to/updatedTemplate.json -Encoding UTF8

Answer №2

One approach is to transform json data into PowerShell objects, apply the necessary modifications, and then convert it back to json format if required.

Here's an illustration:

$data = Get-Content -Path "C:\input.json" | ConvertFrom-Json
$data.items = $data.items | where category -eq 'category1'
$data | ConvertTo-Json -Depth 4 | Out-File "C:\output.json"

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Problem: Values are not being posted with AJAX when using $(form).serialize()

I'm encountering an issue with submitting a form using AJAX. I initially tried to pass the data using $("#myForm").serialize(), but for some reason, the receiving page doesn't receive the data. Take a look at my form: <form id="myForm"> ...

Connecting Alamofire calls using Swift and PromiseKit

My current setup involves utilizing two API endpoints, with the second dependent on the result of the first. The initial endpoint is /api/v1/regions/, which provides a JSON list of regions structured like this: { region_id: 1, mayor_id: 9 }, { regi ...

Utilizing NodeJS to Extract Data from MongoDB and Export to JSON File

I'm struggling to figure out how to write a specific field from my mongodb database to a json file using node js. Can anyone provide guidance or resources? I haven't had much luck finding helpful information so far. ...

How to Send and Receive Data in One Request Using Android Studio and Web API

Currently, I am working on an Android App using Android Studio and the backend is being developed using Asp.Net Web API. Web Api Part [System.Web.Http.AcceptVerbs("GET", "POST")] [System.Web.Http.HttpGet] public dynamic GetTest(string name) { List< ...

Integrating List<class> into class xxx with JSON format

I am attempting to input data into one list and then transfer it to another list `{ { "name": "0001", "id": "donut", "total": { "price": [{ "date": "1001", "type": "Regular" }, { ...

Working with JSON data in Java and displaying it in a user interface

As a newcomer to JAVA, I find myself facing JSON data for the first time. My task is to develop a news desktop application by sending a GET request to a web address that returns JSON output, as illustrated below. ****JSON OUTPUT**** { "status": ...

Error in decoding JSON while creating an index in Azure Search

I'm currently utilizing the django framework and attempting to set up an index in the Azure portal through their REST API guide. However, upon sending my post request, I encountered the following error: JSONDecodeError at /createIndex Here is the m ...

ìdentifying Incomplete JSON Data using Python

I'm currently working on an innovative online weather web application. The goal of this app is to allow users to search for any city or town and instantly receive accurate weather statistics. However, I have encountered a hurdle in my project. The fre ...

Split a column containing JSON stored as a string into individual rows and columns

I am currently working with SQL Server and I have a column that contains JSON data stored as a string. My goal is to explode/normalize this JSON data into new rows and columns. The table's current layout can be seen in the image provided below. Each P ...

Is it possible for Python JSON to encode/decode functions from text files?

Is JSON capable of encoding and decoding functions to and from files, in addition to complex data? ...

Unexpected JSON token error occurs in jQuery when valid input is provided

I encountered an error that I'm struggling to pinpoint. The issue seems to be related to the presence of the ' symbol in the JSON data. After thoroughly checking, I am positive that the PHP function json_encode is not responsible for adding this ...

Transforming AWS CLI DynamoDB JSON output into standard JSON format

Is there a method for transforming the aws cli response for a dynamodb get-item request from dynamodb JSON format to standard JSON format? I am seeking an effective way to version an item that is being updated in a dynamodb table. I have experimented with ...

Managing JSON object with irregular data in Angular 7: Best Practices

When the service returns data in a specific format, I am able to view the data in the developer tools. {"results":{"BindGridDatatable":[{"ID":"0005","Name":"Rohit"}, {"ID":"0006","Name":"Rahul"}], "Totalvalue":119}} ...

reversed json using javascript

Is it possible to efficiently reverse the order of the following JSON object: { "10": "..." "11": "...", "12": "...", "13": "...", "14": "...", } so that it becomes: { "14": "...", "13": "...", "12": "...", "11": "... ...

Grails - JSONBuilder - Specification for toPrettyString() results in a stack overflow exception

I need to create a unit test that returns JSON data. To achieve this, I am utilizing the toPrettyString() method from JSONBuilder. Here is the class under consideration: class Lugar { String sigla String nombre Coordenada coordenada String t ...

Guide on accessing a nested array within a JSON object using JavaScript

I'm currently faced with a json object that contains nested arrays and names with spaces like Account ID. My goal is to only display the Account ID's within my Vue.js application. While I can access the entire response.data json object, I'm ...

Best practices for sending an object from client to server using Node.js

What is the best way to transfer a large object from client side to my node.js server? The object is currently stored in a variable within my script tags. ...

The controller is unable to accept JSON data from the JQuery.ajax function

I have thoroughly checked my web.xml and spring-servlet.xml files, but I couldn't find any issues. I then reviewed my Controller and .ajax() call, but still couldn't identify the problem. I experimented with using JSON.stringify, @RequestParam, a ...

What is the best way to retrieve and manipulate JSON data using Python?

Hey there, I'm fairly new to coding and I've been working on a Python program that reads data from a JSON file and saves only specific information to another file. While researching how to parse the data, I came across something that's confu ...

Utilize Node.js to parse JSON data and append new nodes to the final output

When parsing a JSON object in Node.js, the resulting hierarchical object can be seen in the debugger: datap = object account1 = object name = "A" type = "1" account2 = object name = "B" type = "2" If we want to add ...