Separating JSON objects by their key value

At the moment, I am focused on retrieving the expiry status of Azure AD applications. I have collected approximately 1700 AD applications and added a new key pair (status) to the JSON object based on the expiration date of the secret.

1) valid 2) Expired 3) expiring soon

After extracting all applications into a JSON file, my next task is to divide the single file into three separate files based on the mentioned statuses below:

[
    {
        "DisplayName": "Reporter-dev",
        "ObjectId": null,
        "ApplicationId": {
            "value": "62838283828288282828828288282828",
            "Guid": "62838283828288282828828288282828"
        },
        "KeyId": "62838283828288282828828288282828",
        "Type": "Password",
        "StartDate": {
            "value": "/Date(1590537256000)/",
            "DateTime": "27 May 2020 05:24:16"
        },
        "EndDate": {
            "value": "/Date(1653609256000)/",
            "DateTime": "27 May 2022 05:24:16"
        },
        "Ownername": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="72011a1706060b32151f131b1e5c111d1f">[email protected]</a>",
        "Status": "Valid"
    },
    {
        "DisplayName": "azure-cli-2018",
        "ObjectId": null,
        "ApplicationId": {
            "value": "52388282828828288273673282932739223",
            "Guid": "52388282828828288273673282932739223"
        },
        "KeyId": "52388282828828288273673282932739223",
        "Type": "Password",
        "StartDate": {
            "value": "/Date(1568849784000)/",
            "DateTime": "19 September 2019 05:06:24"
        },
        "EndDate": {
            "value": "/Date(1600472184000)/",
            "DateTime": "19 September 2020 05:06:24"
        },
        "Ownername": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="bad0d5c9dfcad2faddd7dbd3d694d9d5d7">[email protected]</a>",
        "Status": "Expired"
    },
    {
        "DisplayName": "azure-cli-2019",
        "ObjectId": null,
        "ApplicationId": {
            "value": "26382882828828282882828282828",
            "Guid": "26382882828828282882828282828"
        },
        "KeyId": "26382882828828282882828282828",
        "Type": "Password",
        "StartDate": {
            "value": "/Date(1576143476000)/",
            "DateTime": "12 December 2019 15:07:56"
        },
        "EndDate": {
            "value": "/Date(1607765876000)/",
            "DateTime": "12 December 2020 15:07:56"
        },
        "Ownername": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="502a2a2a2a2a2a2a2a10373d31393c7e333f3d">[email protected]</a>",
        "Status": "About to Expire"
    }
]

Answer №1

To extract and separate JSON data based on their status, the below code snippet will be helpful. You can customize the paths in

$JSONPath, $ValidPath, $ExpiredPath, $ExpiredSoonPath
according to your requirements.

Make sure that the content within $JSONPath is valid JSON for this to function correctly. Although not the most efficient or elegant method, it gets the job done.

$JSONPath = "C:\PS\JT\JSON.txt"

$JSONObj = Get-Content $JSONPath | ConvertFrom-Json

$ValidPath = "C:\PS\JT\Valid.txt"
$ExpiredPath = "C:\PS\JT\Expired.txt"
$ExpireSoonPath = "C:\PS\JT\ExpireSoon.txt"


$JSONObj | Where {$_.Status -eq "Valid"} | ConvertTo-Json | Out-File $ValidPath
$JSONObj | Where {$_.Status -eq "Expired"} | ConvertTo-Json | Out-File $ExpiredPath
$JSONObj | Where {$_.Status -eq "About to Expire"} | ConvertTo-Json | Out-File $ExpireSoonPath

Answer №2

If you consider a scenario where something as basic as the example below could be effective, but due to the lack of code visibility, there is a certain level of speculation involved...

$collection = $json | ConvertFrom-Json
$valid = @(); $exp = @(); $soon = @(); $unknown = @()

foreach($item in $collection) {
    
    switch ($item.Status)
    {
        'Valid' { $valid += $item }
        'Expired' { $exp += $item }
        'About to Expire' { $soon += $item }
            Default { $unknown += $item}
    }
}

$valid | Out-File .\Valid.txt -Append
$exp | Out-File .\Expired.txt -Append
$soon | Out-File .\AboutToExpire.txt -Append
$unknown | Out-File .\Unknown.txt -Append

Alternatively, if the desired output is in JSON format as shown in the previous example;

$valid | ConvertTo-Json | Out-File .\Valid.txt -Append

and so forth

Answer №3

In addition to the existing responses, here is another approach utilizing pipelines.

Get-Content -Path .\sample.json -Raw | ConvertFrom-Json | 
    ForEach-Object { $_ | ConvertTo-Json | Out-File -FilePath "$($_.Status).json" }

Breakdown

  • Extract JSON data using Get-Content, ensuring the usage of the -Raw parameter to receive the data as a single string while preserving line breaks instead of an array of strings(default behavior).
  • Pipe the data into ConvertFrom-Json for deserialization into a
    System.Management.Automation.PSCustomObject
    .
  • Iterate through the objects using Foreach-Object and convert each object into a JSON file using ConvertTo-Json along with Out-File. Note that the default depth for ConvertTo-Json is 2, so adjust the depth using the -Depth parameter if your JSON files have deeper levels.

If it helps with clarity, a traditional foreach loop can also be utilized:

$json = Get-Content -Path .\sample.json -Raw | ConvertFrom-Json

foreach ($object in $json) {
    $object | ConvertTo-Json | Out-File -FilePath "$($object.Status).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

Can you explain the concept of being "well-typed" in TypeScript?

The website linked below discusses the compatibility of TypeScript 2.9 with well-defined JSON. What exactly does "well-typed" JSON mean? As far as I understand, JSON supports 6 valid data types: string, number, object, array, boolean, and null. Therefore, ...

Transforming Thomas J Bradley's signature pad JSON into a PNG file using C# programming language

I have been experimenting with the Signature Pad plugin developed by Thomas J Bradley and successfully converted JSON signature to PNG using PHP. Now I am looking to achieve the same result using C#. There is a supplemental class called SignatureToImageDo ...

Accessing the Key Name of a JSON Array in Android Using Dynamic Methods

I have a unique json url, which upon opening displays the following data { "Response": "Successful", "All_Items": [{ "Category": "1", "TotalCount": "5", "ExpiringToday": 2 }], "TopOne": [{ "id": "10", "ThumbnailPath": "http://exampleo ...

Are all of the User columns in my database on Parse.com marked as undefined?

Yesterday, a strange problem occurred in my code while setting up a User on Parse to include profile information. Despite correctly retrieving data from Parse within the app, all user profile fields on Parse.com are marked as undefined. I suspect a JSON ...

Leveraging AJAX for connectivity to the Twitter API

Considering incorporating Twitter functionality into my web application, I decided to conduct some tests. After researching how to call the search Twitter URL (more information available at: ) in order to retrieve tweets containing specific words or phrase ...

Using Jquery to send json data to a webserver via Ajax (API)

Currently, I am attempting to use AJAX to post data to a JSON file (API) on a server. As part of this process, I have implemented dragging functionality for two Kineticjs shapes on the stage. Upon stopping the drag action, my goal is to save the updated x ...

What is the best way to iterate through this array in ajax?

Is there a way to properly read this array using ajax? I need some assistance understanding the server response: Array ( [success] => 1 [0] => Array ( [0] => Mr Green [FirstName] => Mr Green ...

sending a POST request with multiple parts using d3.json() or d3.xhr()

Currently, there seems to be a lack of support for submitting multipart form data with a request. While I understand how to perform a POST with d3.json().post() as outlined in this resource, I am specifically interested in using POST to submit parameters t ...

Step-by-step guide on retrieving the 'No User found' message from the specified variable in a Node.js environment

Is it possible to extract the 'No User found' message from the following variable using Node.js? {"error":["No User found."]} ...

Obtaining a worldwide JavaScript variable through AJAX JSON query

Hello, I have encountered an issue while using this code for my AJAX JSON request. When attempting to make jsonObj a global variable and then console.log() it, the debugger console shows that it is always coming up as undefined. To explain my question fur ...

Arranging JSON data by a specific attribute using JavaScript

As someone who is new to JavaScript, I have been working on some basic exercises. In my current code, I have a JSON data stored in a String that contains information about employees. My goal is to sort this data based on the age attribute and display the o ...

How to use jQuery to dynamically generate a JSON object within a loop

http://jsfiddle.net/hU89p/219/ This example demonstrates the creation of a JSON object based on selected checkboxes. When selecting one checkbox, the JSON would look like: var data={"name":"BlackBerry Bold 9650", "rating":"2/5", "Location":UK}; By sele ...

The current project does not have Json enabled for BIGQUERY

Currently, I am working with Bigquery and the data is coming from firestore. However, all of the schema data is in string format, and I need to convert them to JSON format. I attempted to use PARSE_JSON or TO_JSON for this conversion process but encounte ...

Using jquery and Ajax to extract data from nested JSON structures

Need help with modifying a code snippet for parsing nested JSON format [ { "name":"Barot Bellingham", "shortname":"Barot_Bellingham", "reknown":"Royal Academy of Painting and Sculpture", "bio":"Barot has just finished his final year at T ...

Show a dynamic dropdown box using AJAX if a specific variable is present

I am currently working on implementing an ajax call for a dynamic dropdown box. Once the variable $place is available, it triggers an ajax call to populate the dropdown box. My goal is to pass the variable $place to listplace.php, encode it as JSON data ...

Generate a JSON file in accordance with a specified template

I have a file .csv structured like this: ID;Name;Sports 1;Mark;["Football", "Volleyball"] 2;Luuk;["Fencing"] 3;Carl;["Swimming", "Basketball"] My objective is to convert this data into a .json file with th ...

How can I asynchronously parse JSON data from a URL on a Windows phone and display it in a

As an Android developer exploring the world of Windows Phone for the first time, I came across this resource on how to handle list boxes in Windows Phone 7/8. However, my challenge now is parsing JSON from a URL instead of XML as shown in the example. Whil ...

Calculate the number of days required for the value in an item to multiply by two

I'm currently working on a JavaScript project to create a table displaying the latest number of coronavirus cases. I've reached a point where I want to add a column showing how many days it took for the confirmedCases numbers to double. Here&apos ...

Transforming objects into JSON format using C#

I have a class: public class CustomerStatistics { public string data { get; set; } public string xkey {get;set;} public Array ykey {get;set;} public Array labels {get;set;} } How can I achieve JSON output like this? { "data":[ ...

Capturing information from deeply nested JSON structures using Pandas

Currently, I am navigating through a nested JSON structure to retrieve transaction data from my database using the pandas library. The JSON data I am working with can have different structures: {"Data":{"Parties":[{"ID":" ...