Using a for loop or a while loop in Powershell to iterate through a JSON object

Hey there, I'm new to Powershell and looking for some help with looping. Can someone assist me with this? Below is the JSON format from a file called Test.json:

{
    "Pre-Production_AFM": {
        "allowedapps": ["app1", "app2"]
    },
    "Production_AFM": {
        "allowedapps": ["app1", "app2"]
    }
}

This is how I am currently reading the JSON file:

$json = (Get-Content "Test.json" -Raw) | ConvertFrom-Json

I need to loop through and extract the 1st and 2nd objects dynamically - "Pre-Production_AFM" and "Production_AFM" one after the other.

Here's the code I have so far:

foreach($i in $json){

        if($i -contains "AFM"){
       Write host "execute some code"
     }
}

I'm unsure if $i will contain the object "Pre-Production_AFM" dynamically or not. If not, please advise on how to iterate through the objects sequentially for further processing. Thanks!

Answer â„–1

# accessing and manipulating JSON data in PowerShell
$jsonData = @"
{
    "Pre-Production_AFM": {
        "allowedapps": ["app1", "app2"]
    },
    "Production_AFM": {
        "allowedapps": ["app1", "app2"]
    }
}
"@

# converting JSON to a PSCustomObject
$dataObject = $jsonData | ConvertFrom-Json

# checking the type of the object
$dataObject.GetType().FullName
# System.Management.Automation.PSCustomObject

# filtering properties by name and performing operations
$afmProperties = $dataObject.psobject.Properties | where-object { $_.Name -like "*_AFM" };

# iterating through all properties with matching names
foreach( $property in $afmProperties )
{
   $allowedAppsList = $property.Value.allowedApps
   # do necessary tasks here
}

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

A comparison of parent and child components

To implement a child-parent component relationship in Angular, first create two JSON files: parent.json and child.json. The parent.json file should contain the following data: "Id":10001, "name":"John" "Id":10002, ...

How to Retrieve Video Length using AJAX in the YouTube API

I have been working on a script to fetch the duration of a YouTube video using its id. Here is the code snippet I've written: var vidID = ""; var vidData; var vidDuration; function getResponse() { $.getJSON( "https://www.googleapis.c ...

Utilize a for loop in Vue.js to save a fresh array of objects in a structured format

Trying to achieve the following using Vue: I have two JSON objects that provide information on languages and the number of inputs per language. Using nested loops, I display all the inputs. My goal is to create an object for each input with additional det ...

Efficient Local Database with Javascript

When storing a substantial amount of data, such as a big hashmap in JavaScript, what would be the optimal format for quick retrieval while also supporting Unicode? Would XML or JSON be better suited for this purpose? ...

Transforming a single object into multiple arrays using AngularJS

Just starting out with AngularJS and I've got some data that looks like this { day1: 0, day2: 0, day3: 0, day4: 2 } Is there a way to convert this data into arrays structured like below? [     ["day1": 0],     ["day2": 0],   ...

Ways to dynamically fetch data by merging the response outcome with a dynamic parameter from the route in Vue.js

For the first time, I have been tasked with dynamically retrieving object parameters from the URL parameter. I am aware that I can use this.$route.params.[somelink-parameter] to obtain the URL parameter, and I understand how to retrieve and store the respo ...

Ng-repeat seems to be having trouble showing the JSON data

Thank you in advance for any assistance. I have a factory in my application that utilizes a post method to retrieve data from a C# function. Despite successfully receiving the data and logging it to the console, I am facing difficulties in properly display ...

Exploring Data within Data Structures

I am currently making two JSON requests in my code: d3.json("path/to/file1.json", function(error, json) { d3.json("path/to/file2.json", function(error, json2) { }); }); The structure of json 2 looks like this: [ { "city" : "LA", "locati ...

A guide on organizing nested JSON objects in JavaScript

I am currently using JavaScript to retrieve JSON data that looks like this: [{ "data": { "serialNumber": "12345678", "loopCount": 2, "temperature3": 22.74921781259558, "temperature2": 21.459065450414467, "temper ...

Encountering an issue with Vue JS axios request and filter: the function this.XX.filter is not operational

I am encountering challenges while trying to implement a basic search feature on a JSON file obtained through an API. Each component works independently: I can successfully retrieve data from the API, perform searches on non-API data, and even search cert ...

How can I send data in JSON format to a JavaScript AJAX request?

I've created a method that looks like this: public String getUTResult() throws IOException { BuildResultParser bp = new BuildResultParser(); BuildResultBean b = bp.getreadFile("C:\\bc.txt"); String str = b.getuTresult(); ...

Storing JSON data retrieved from a fetch API request in a JavaScript global variable - a beginner's guide

I have been experimenting with the fetch API and successfully managed to log the fetched data to the console using the then() method. However, I am struggling to store this data in a global variable for later use in vanilla javascript due to the nature of ...

Angular $resource encounters a 400 Bad Request error when attempting a PUT request, triggering the $resolve and $promise

My service is structured as follows (with variables removed): angular .module('app') .factory('Employee', function($resource) { return $resource("https://api.mongolab.com/api/1/databases/:dbName/collections/:collectionN ...

retrieving JSON data within the controller

When I use the command console.log($scope.data), I am able to view my JSON file. Additionally, by using <div ng-repeat="item in data">, I can see all the items in the view. However, when I try console.log($scope.data[0]) or console.log($scope.data[0] ...

Managing additional components in request JSON when communicating with DialogFlow, previously known as Api.ai

My current challenge involves enhancing the information sent in a JSON request from my application to DialogFlow. While I am familiar with triggering events to send data calling an intent through the method described in Sending Parameters in a Query Reques ...

Encountering a missing value within an array

Within my default JSON file, I have the following structure: { "_name":"__tableframe__top", "_use-attribute-sets":"common.border__top", "__prefix":"xsl" } My goal is to add values by creating an array, but I am encountering an issue where my ...

Prepending a string to the key of a JSON object using JavaScript

Is there a way to add 'd:' before the key of a JSON object? Here is the JSON data: "data": { "aa": "value", "ab": "value" } The expected result should look like this: "d:data": ...

I'm just starting out with jQuery and JSON and could use some assistance with formatting the string, specifically so I can properly iterate through it

This is the controller. <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> @RequestMapping("/getDropDownAjax") public void fetchData(HttpServletRequest req,HttpServletResponse resp){ System.out.println ...

Converting a text file to JSON format using Adobe Acrobat: A tutorial on proper referencing

I am facing an issue with converting a string from a file attached to my PDF (JSONTEST.txt) into JSON format so that I can reference it using obj[key]. Despite trying to use eval(), I encounter the following error every time: SyntaxError: missing ; before ...

Is there a way to properly structure the json data displayed in my network tab on Chrome?

After sending an http request to my backend, I received a json response in the network tab. However, the format of the json is unreadable. To clarify, here is a screenshot: https://i.stack.imgur.com/RBiTd.png Currently using Chrome, I am seeking assistanc ...