How can I generate a sorted array of objects in a JSON output using PowerShell?

Is it possible to generate a JSON output with an array of objects sorted in ascending order based on the "count" property? I need to maintain the original $result object structure, without caring about the order of "Good" or "Bad", My goal is to sort the objects within the arrays by the "count" property.

This is my current code:

$result = [PSCustomObject]@{
    Good = @() 
    Bad  = @()
}

$food = [PSCustomObject]@{
    name  = "Banana"
    count = 2
}

if ($food.count -gt 3) { $result.Good += $food }
else { $result.Bad += $food }

$sortGood = $result.Good | Sort-Object count
$sortBad = $result.Bad | Sort-Object count
Write-Output ($result | ConvertTo-Json)

The current JSON output is as follows:

{
    "Good": [
                {
                    "name": "Apple"
                    "count": 10
                },
                {
                    "name": "Lime"
                    "count": 5
                },
                {
                    "name": "Peach"
                    "count": 7
                }
            ],
    "Bad": [
                {
                    "name": "Banana"
                    "count": 2
                },
                {
                    "name": "Kiwi"
                    "count": 1
                },
                {
                    "name": "Orange"
                    "count": 3
                }
            ] 
}

How can I achieve a desired JSON format like this? (fruits sorted by "count" property in ascending order)

{
    "Good": [
                {
                    "name": "Lime",
                    "count": 5
                },
                {
                    "name": "Peach",
                    "count": 7
                },
                {
                    "name"": "Apple",
                    "count": 10
                },
            ],
    "Bad": [
                {
                    "name""": "Kiwi"",
                    "count":: 1
                },
                {
                    "name" :: "Banana"",
                    "count", 2
                },
                {
                    "name""": "Orange"",
                    "count": 3
                }
            ] 
}

[Issue Resolved] Revised solution:

$result.Good = $result.Good | Sort-Object count
$result.Bad  = $result.Bad | Sort-Object count
Write-Output ($result | ConvertTo-Json)

Answer №1

Sort-Object doesn't actually "sort the object". It simply returns a sorted copy of the object. Therefore, when you use:

$sortGood = $result.Good | Sort-Object count

The variable $sortGood will be properly sorted, while $result.Good remains unchanged.

$json = @"
{
    "Good": [
        {"name": "Apple", "count": 10},
        {"name": "Lime", "count": 5},
        {"name": "Peach", "count": 7}
    ],
    "Bad": [
        {"name": "Kiwi", "count": 1},
        {"name": "Orange", "count": 4}
    ] 
}
"@

$data = ConvertFrom-Json $json

$food = @{
    name  = "Banana"
    count = 2
}

if ($food.count -gt 3) {
    $data.Good += $food
} else {
    $data.Bad += $food
}

$data.Good = $data.Good | Sort-Object count
$data.Bad = $data.Bad | Sort-Object count

$result = $data | ConvertTo-Json -Depth 10
$result

This code block results in:

{
    "Good":  [
                 {
                     "name":  "Lime",
                     "count":  5
                 },
                 {
                     "name":  "Peach",
                     "count":  7
                 },
                 {
                     "name":  "Apple",
                     "count":  10
                 }
             ],
    "Bad":  [
                {
                    "name":  "Kiwi",
                    "count":  1
                },
                {
                    "count":  2,
                    "name":  "Banana"
                },
                {
                    "name":  "Orange",
                    "count":  4
                }
            ]
}

It's important to note that I consistently update the values of $data.Good and $data.Bad:

  • Using $data.Good += $food creates a new array with $food added at the end, which is then assigned to $data.Good. (This is shorthand for $data.Good = $data.Good + $food.)
  • Using
    $data.Good = $data.Good | Sort-Object count
    also creates a new array with a different order based on the sorting criteria, and then assigns it to $data.Good.

Answer №2

Hello! It seems like you might have overlooked adding -Property after Sort-Object in your code snippet. Here's the corrected version:

$sortedList = $data.List | Sort-Object -Property Name

Feel free to test it out and share your results with me!

Answer №3

This is how I would approach it:

ConvertTo-Json @{
    Positive = $result.Positive | sort Count
    Negative = $result.Negative | sort Count
}

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

Leverage decodable for personalized JSON parsing

I possess a json in this particular structure: { "route":{ "1":"Natural Attractiveness", "2":"Cultural Attractiveness", "3":"For Families with Children", "5":"For Seniors", "6":"For Eagles", "8":"Disabled" }, ...

The annotations are not appearing on the mapview as expected due to a

I am having trouble displaying information on a map from a JSON file. It seems like something is missing in order to show the data on the map. I have successfully implemented the JSON functionality and logged the information, but now I need help creating t ...

Unable to retrieve information from compact JSON files

It's been 2 hours and I still can't figure this out I need help with reading my Json Data in my JavaScript File, saving it to a variable, and then printing it out. I've tried multiple solutions but nothing seems to work (I'm new to ...

A guide to dynamically extracting values from JSON objects using JavaScript

I have a JSON array with a key that changes dynamically (room number varies each time I run the code). My goal is to access the inner JSON array using this dynamic key. Here's what I've attempted so far, but it's throwing an error. Here is ...

Unable to Access ReactJS Nested Property in JSON Data

While attempting to access a nested property in my JSON file loaded into the state, I encountered an issue. Despite confirming the existence of the property within the object through logging, when trying to navigate a level deeper using dot-notation, an er ...

What is the best way to convert an object to JSON and transmit it to a web service?

Is there a way to convert an object into json and then send it to a web service? var object = something.... function BindJson() { $.ajax({ type: "POST", url: "NewPage.aspx/GetJson", data: "{}", conte ...

How can I insert a item into an Array using JavaScript code?

My instructor set up an array in my JavaScript file that is off limits for me to modify. My task is to add new objects to it through code without directly manipulating the existing array. Here's a snapshot of what my array contains: const words = [{ ...

Add a new key-value pair to the mock data by clicking on it

Hey there! I'm currently tackling a task that involves toggling the value of a boolean and then appending a new key-value pair on click. I've been attempting to use the . operator to add the new key-value pair, but it keeps throwing an error. In ...

What is the best way to iterate over an array of objects?

I have an Array of Objects that I need to use in order to create an HTML Table: Array(5) 0: Object id: 4 name: Sand Jane address: Green Sand Street ... ... ... 1: Object 2: Object ... ... ... Currently, I am able to perform a search wit ...

Using AngularJS to create a form and showcase JSON information

My code is below: PizzaStore.html: <!DOCTYPE html> <html ng-app="PizzaApp"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Delicious pizza for all!</title> ...

Encountering a problematic JQuery Ajax request to a RESTful API

I am currently in the process of trying to authenticate against demo webservices that were developed by one of my colleagues. While Cross-origin resource sharing is allowed and functions perfectly when I attempt to call from the Advanced Rest Client plugin ...

I tried implementing a progress bar for my JSON post and response, but unfortunately, it is not displaying as expected

I have successfully implemented JSON data posting to the server. However, I am facing an issue with integrating a progress bar to show the progress. The progress bar is not displaying at all despite the data being posted and response received. @Override ...

Retrieve filled out form fields in ServiceM8

Is there a way to retrieve completed form field data in ServiceM8, including uploaded images? I've looked through the API reference but couldn't find any information on how to access them. Can someone share an example or provide documentation on ...

Exploring the concept of accessing multidimensional arrays in PHP using keys

This is the result retrieved from the server: Array ( [id] => 123 [status] => pending [recipient] => Array ( [account_id] => 5000 [gateway_id] => 51111 ) [amount] => Array ( [value] => 2 [currency] => RUB ) [description] => orde ...

What is the best way to add JSON data to a table?

I have developed a php script to create json data. However, I am facing an issue while trying to display this generated json data in a table. While my php code successfully generates the data, it is unable to insert it into the table. I would appreciate an ...

The Alphavantage was acting strangely when I ran a Google script

After following a tutorial video on YouTube, I was confident that my Google script for Google Sheets was working perfectly. However, I encountered two strange issues that I just can't seem to figure out. The code below is exactly what I need - it ...

JavaScript: Creating an array of images from a directory

I've encountered a problem that has proven to be more complex than expected - I am struggling to find resources related to my specific question. My goal is to store 36 images from a folder on my computer into an array using Javascript. Below, you will ...

Convert a multidimensional array into a string using JavaScript

Currently, I'm in the process of generating an invoice for a collection of books and my intent is to submit it using ajax. However, when attempting to json encode the array of books within the invoice, I am encountering a setback where the value keeps ...

Deconstructing a JSON Structure

I'm currently developing a D3 damage per second (DPS) calculator and encountering an issue with a JSON object. The JSON object I receive looks like this: {"Sockets":{"min":1,"max":1}, "Dexterity_Item":{"min":165,"max":165}, "Durability_Cur":{"min":58 ...

I am facing difficulties in adding dynamic content to my JSON file

I've encountered a challenge in appending new dynamic data to a JSON file. In my project, I receive the projectName from an input form on the /new page. My API utilizes node.js's fs module to generate a new JSON file, where I can subsequently add ...