cancel
Showing results for 
Search instead for 
Did you mean: 
Reply
nikviz
Resolver II
Resolver II

find top three values in json array

Hello,

 

I am trying to build a interactive chatbot using PVA, where user interaction is fed to AI models and the model response is sent back. I get the model response as below:

 

sample json:

[
  {
    "label""Car",
    "score"0.23
  },
  {
    "label""Bus",
    "score"0.26
  },
  {
    "label""Train",
    "score"0.34
  }
{
    "label""Boat",
    "score"0.45
  }
{
    "label""Truck",
    "score"0.62
  }
{
    "label""Bike",
    "score"0.11
  }
]
 
I need to get the top three label based on the score.. for this example: Truck, Boat, Train should be returned, that needs to be fed back to PVA.
This is the flow, I've made, and stuck on how to get the top three. Any inputs or links would help. Thanks
nikviz_0-1654598015675.png

 

 
 
2 ACCEPTED SOLUTIONS

Accepted Solutions

The one thing that I can't see mentioned, here, @nikviz, is whether or not there is a catering for the fact that there's the remotest possibility that two scores may be the same, and those two scores may be in that top three ... potentially making it a top 4/5/6/etc. 😉

 

Obviously I've not just come to troll, though.

 

I'm sure that @Paulie78's xpath() awesomeness will easily overshadow what I've done here, and will take far fewer steps.

 

Either way, this will provide the top three values, even if those may be shared, and then returns a new array of just the top items.

 

Here's the sample data that I used, I simply made two items (boat+train) have the same, second highest, value:

Spoiler
[
	{
		"label": "Car",
		"score": 0.23
	},
	{
		"label": "Bus",
		"score": 0.26
	},
	{
		"label": "Train",
		"score": 0.45
	},
	{
		"label": "Boat",
		"score": 0.45
	},
	{
		"label": "Truck",
		"score": 0.62
	},
	{
		"label": "Bike",
		"score": 0.11
	}
]

 

Doing The 'Long' Way ... Without xPath()

OK, the only real complicated bit in this is that I decided to give you a 'position' to indicate which value is in which position. This is totally optional, and I'll ensure that you know what to do to carry on without that.

 

Here's the flow!

0 - The Flow.jpg

 

I'll now go through each action, where you see a code box that will be an expression unless otherwise noted.

 

Select scores

OK, this is the only thing where the image is a bit off, because I left an old expression in the note there, ignore that.

1 - Select Scores.jpg
From currentArrVAR
Map
item()?['score']

 

Initialising Variables

This should be simple, each of these is either empty or easily understood.

Name Type Value Description
topArrVAR Array   This will hold the top valued items
maxesVAR Array Select scores This makes it easier to know purely an array of the values
iterationVAR Integer 0 This contains the current loop number the Do until is on
maxVAR Float   This contains the current maximum value in the maxesVAR

 

Do until

Here's the sauce, this will run until the iterationVAR is equal to 2, which means that it will have run 3 times as the first iteration is 0.

2 - Do until.jpg

Hopefully it's relatively obvious that you simply choose the Dynamic value of iterationVar in the left side, select the condition 'is equal to', then put a number 2 in the right side of this.

 

Set maxVAR

This is the first real key part, this looks at the current values in the maxesVAR array, and selects the highest one to set as its value:

3 - Set maxVAR.jpg

max(variables('maxesVAR'))

 

Set iterationVAR

This replaces whatever number is already in iterationVAR with the current iteration of the Do until loop.

4 - Set iterationVAR.jpg

iterationIndexes('Do_until')

 

Next you need to filter a few things, so these will have their conditions represented here in their advanced mode, but you can probably see how to set them.

Filter is branch

The Filter is action filters the currentArrVAR variable by the maxVAR value, returning all items where item()?['score'] matches that value.

05 - Filter is.jpg
From currentArrVAR
Condition
@equals(item()?['score'], variables('maxVAR'))

Now that you have the list of items which match the highest value you can add those to the topArrVAR.

 

The Body in that Apply to each here what happens when you select the Filter is Dynamic value:

06 - Apply to each.jpg

addProperty(
    items('Apply_to_each'), 
    'position', 
    add(variables('iterationVAR'), 1)
)
The addProperty() function here is the optional part that I mentioned earlier. If you prefer to just have the original fields, simply use:
items('Apply_to_each')

 

Filter remainingMaxes branch

This filters the maxesVAR array to return every item() which is NOT the maximum value:

07 - Filter remainingMaxesVAR.jpg
From maxesVAR
Condition
@not(equals(item(), variables('maxVAR')))

Now that you have filtered the maxesVar to everything EXCEPT the maximum value (maxVAR) you can set the maxesVAR to a new set of values which don't contain it ... this allows the next loop to pick the next highest value!

08 - Set maxesVAR.jpg

body('Filter_remainingMaxes')

 

Filter nots branch

This filters the currentArrVAR down to every item()?['score'] that DOES NOT match the maximum number (maxVAR).

09 - Filter notsVAR.jpg
From currentArrVAR
Condition
@not(equals(item()?['score'], variables('maxVAR')))

Now that you have an array which does not contain the current top values, you can Set currentArrVAR to contain that array, instead of its old set of data, meaning that the previous top value is gone:

10 - Set currentArrVAR.jpg

body('Filter_nots')

 

That's it ... now your topArrVAR will hold the top three valued items, even if that is more than 3!

 

HURRAH!!

 

Any Potential Issues?

Well, the only one I can think of is potential 'concurrency' issues inside the 'Do until', but I don't think it will be an issue.

 

But if you wanted to be super sure, then you would run the 'Filter nots' branch after the other two, which should be fine next to each other.

View solution in original post

This is my take on it:

https://www.tachytelic.net/2022/07/power-automate-sort-json-array/

 

It was a fun problem to solve, thank you for posting it 😀

 

Blog: tachytelic.net

YouTube: https://www.youtube.com/c/PaulieM/videos

If I answered your question, please accept it as a solution 😘

View solution in original post

11 REPLIES 11
Expiscornovus
Most Valuable Professional
Most Valuable Professional

Hi @nikviz,

 

Which endpoint are you using in your HTTP action? Maybe it would be possible to add $sort query parameter in the specific HTTP request if that endpoint supports it. 

 

Can you share a screenshot of your HTTP action config?



Happy to help out! 🙂

Interested in more #PowerAutomate #SharePointOnline or #MicrosoftCopilotStudio content?
Visit my blog, Subscribe to my YouTube channel or Follow me on Twitter


nikviz
Resolver II
Resolver II

Hello @Expiscornovus 

 

nikviz_1-1654599319410.png

 

Expiscornovus
Most Valuable Professional
Most Valuable Professional

Hi @nikviz,

Thanks for sharing that screenshot. I have had a quick look in the Inference API documentation. I did not find any $sort or $top parameters so far.

 

I assume you are using one of the Natural Language Processing tasks listed in the documentation below (Named Entity Recognition (NER) task by any chance?)

https://huggingface.co/docs/api-inference/detailed_parameters

 

Let me see if I can share a workaround to sort on score descending and get top 3 afterwards.

 



Happy to help out! 🙂

Interested in more #PowerAutomate #SharePointOnline or #MicrosoftCopilotStudio content?
Visit my blog, Subscribe to my YouTube channel or Follow me on Twitter


nikviz
Resolver II
Resolver II

Hello @Expiscornovus 

 

Thanks a lot for looking into this. I am using a custom Natural Language model to classify certain Categories. so from the link https://huggingface.co/docs/api-inference/detailed_parameters#text-classification-task this seems to be the closest.

 

Is it possible to get the top score and the corresponding label from that json format. I can use this as a temporary solution. Like the value returned from the JSON should be "Truck" as it has the highest score.

I tried this tutorial (https://www.youtube.com/watch?v=weNI78Z1FBo) to get the highest "score", but not sure how the get the associated label. 

 

Thanks a lot for your help
 

Expiscornovus
Most Valuable Professional
Most Valuable Professional

Hi @nikviz,

 

You can probably use an Office Script for this. @Paulie78 has written a nice blog about this approach:

https://www.tachytelic.net/2021/03/power-automate-sort-array/

 

Another approach could be to turn your response into xml and use xpath. But that does require some xpath knowledge and can be a bit more complicated.



Happy to help out! 🙂

Interested in more #PowerAutomate #SharePointOnline or #MicrosoftCopilotStudio content?
Visit my blog, Subscribe to my YouTube channel or Follow me on Twitter


I have figured out a way of doing this (with xpath) natively in Power Automate without using an Office Script. It's quite an interesting problem. So I am going to write it up into a blog post next week and will post the link here.

nikviz
Resolver II
Resolver II

Thank you so much @Expiscornovus and @Paulie78 
Will surely try to implement the xpath method once the blog is out as I do not have access to use Office Script.

 

As a temporary workaround to fetch the corresponding label associated with highest "score"  @abm helped me out.

 

 

nikviz
Resolver II
Resolver II

I forgot to update this.. as a temporary workaround
I managed to solve it by:

1) Finding the maximum value from array1 -> lets call it max1

2) Filter out max1 from array and call it array2

3) Find the maximum value from array2 -> call it max2

4) Filter out max2 from array2 and call it array3

5) Find the maximum value from array3 -> call it max3

 

max1, max2 and max3 are the top three values

I will try to post my solution tonight, It's pretty neat actually.

The one thing that I can't see mentioned, here, @nikviz, is whether or not there is a catering for the fact that there's the remotest possibility that two scores may be the same, and those two scores may be in that top three ... potentially making it a top 4/5/6/etc. 😉

 

Obviously I've not just come to troll, though.

 

I'm sure that @Paulie78's xpath() awesomeness will easily overshadow what I've done here, and will take far fewer steps.

 

Either way, this will provide the top three values, even if those may be shared, and then returns a new array of just the top items.

 

Here's the sample data that I used, I simply made two items (boat+train) have the same, second highest, value:

Spoiler
[
	{
		"label": "Car",
		"score": 0.23
	},
	{
		"label": "Bus",
		"score": 0.26
	},
	{
		"label": "Train",
		"score": 0.45
	},
	{
		"label": "Boat",
		"score": 0.45
	},
	{
		"label": "Truck",
		"score": 0.62
	},
	{
		"label": "Bike",
		"score": 0.11
	}
]

 

Doing The 'Long' Way ... Without xPath()

OK, the only real complicated bit in this is that I decided to give you a 'position' to indicate which value is in which position. This is totally optional, and I'll ensure that you know what to do to carry on without that.

 

Here's the flow!

0 - The Flow.jpg

 

I'll now go through each action, where you see a code box that will be an expression unless otherwise noted.

 

Select scores

OK, this is the only thing where the image is a bit off, because I left an old expression in the note there, ignore that.

1 - Select Scores.jpg
From currentArrVAR
Map
item()?['score']

 

Initialising Variables

This should be simple, each of these is either empty or easily understood.

Name Type Value Description
topArrVAR Array   This will hold the top valued items
maxesVAR Array Select scores This makes it easier to know purely an array of the values
iterationVAR Integer 0 This contains the current loop number the Do until is on
maxVAR Float   This contains the current maximum value in the maxesVAR

 

Do until

Here's the sauce, this will run until the iterationVAR is equal to 2, which means that it will have run 3 times as the first iteration is 0.

2 - Do until.jpg

Hopefully it's relatively obvious that you simply choose the Dynamic value of iterationVar in the left side, select the condition 'is equal to', then put a number 2 in the right side of this.

 

Set maxVAR

This is the first real key part, this looks at the current values in the maxesVAR array, and selects the highest one to set as its value:

3 - Set maxVAR.jpg

max(variables('maxesVAR'))

 

Set iterationVAR

This replaces whatever number is already in iterationVAR with the current iteration of the Do until loop.

4 - Set iterationVAR.jpg

iterationIndexes('Do_until')

 

Next you need to filter a few things, so these will have their conditions represented here in their advanced mode, but you can probably see how to set them.

Filter is branch

The Filter is action filters the currentArrVAR variable by the maxVAR value, returning all items where item()?['score'] matches that value.

05 - Filter is.jpg
From currentArrVAR
Condition
@equals(item()?['score'], variables('maxVAR'))

Now that you have the list of items which match the highest value you can add those to the topArrVAR.

 

The Body in that Apply to each here what happens when you select the Filter is Dynamic value:

06 - Apply to each.jpg

addProperty(
    items('Apply_to_each'), 
    'position', 
    add(variables('iterationVAR'), 1)
)
The addProperty() function here is the optional part that I mentioned earlier. If you prefer to just have the original fields, simply use:
items('Apply_to_each')

 

Filter remainingMaxes branch

This filters the maxesVAR array to return every item() which is NOT the maximum value:

07 - Filter remainingMaxesVAR.jpg
From maxesVAR
Condition
@not(equals(item(), variables('maxVAR')))

Now that you have filtered the maxesVar to everything EXCEPT the maximum value (maxVAR) you can set the maxesVAR to a new set of values which don't contain it ... this allows the next loop to pick the next highest value!

08 - Set maxesVAR.jpg

body('Filter_remainingMaxes')

 

Filter nots branch

This filters the currentArrVAR down to every item()?['score'] that DOES NOT match the maximum number (maxVAR).

09 - Filter notsVAR.jpg
From currentArrVAR
Condition
@not(equals(item()?['score'], variables('maxVAR')))

Now that you have an array which does not contain the current top values, you can Set currentArrVAR to contain that array, instead of its old set of data, meaning that the previous top value is gone:

10 - Set currentArrVAR.jpg

body('Filter_nots')

 

That's it ... now your topArrVAR will hold the top three valued items, even if that is more than 3!

 

HURRAH!!

 

Any Potential Issues?

Well, the only one I can think of is potential 'concurrency' issues inside the 'Do until', but I don't think it will be an issue.

 

But if you wanted to be super sure, then you would run the 'Filter nots' branch after the other two, which should be fine next to each other.

This is my take on it:

https://www.tachytelic.net/2022/07/power-automate-sort-json-array/

 

It was a fun problem to solve, thank you for posting it 😀

 

Blog: tachytelic.net

YouTube: https://www.youtube.com/c/PaulieM/videos

If I answered your question, please accept it as a solution 😘

Helpful resources

Announcements

Community will be READ ONLY July 16th, 5p PDT -July 22nd

Dear Community Members,   We'd like to let you know of an upcoming change to the community platform: starting July 16th, the platform will transition to a READ ONLY mode until July 22nd.   During this period, members will not be able to Kudo, Comment, or Reply to any posts.   On July 22nd, please be on the lookout for a message sent to the email address registered on your community profile. This email is crucial as it will contain your unique code and link to register for the new platform encompassing all of the communities.   What to Expect in the New Community: A more unified experience where all products, including Power Apps, Power Automate, Copilot Studio, and Power Pages, will be accessible from one community.Community Blogs that you can syndicate and link to for automatic updates. We appreciate your understanding and cooperation during this transition. Stay tuned for the exciting new features and a seamless community experience ahead!

Summer of Solutions | Week 4 Results | Winners will be posted on July 24th

We are excited to announce the Summer of Solutions Challenge!    This challenge is kicking off on Monday, June 17th and will run for (4) weeks.  The challenge is open to all Power Platform (Power Apps, Power Automate, Copilot Studio & Power Pages) community members. We invite you to participate in a quest to provide solutions to as many questions as you can. Answers can be provided in all the communities.    Entry Period: This Challenge will consist of four weekly Entry Periods as follows (each an “Entry Period”)   - 12:00 a.m. PT on June 17, 2024 – 11:59 p.m. PT on June 23, 2024 - 12:00 a.m. PT on June 24, 2024 – 11:59 p.m. PT on June 30, 2024 - 12:00 a.m. PT on July 1, 2024 – 11:59 p.m. PT on July 7, 2024 - 12:00 a.m. PT on July 8, 2024 – 11:59 p.m. PT on July 14, 2024   Entries will be eligible for the Entry Period in which they are received and will not carryover to subsequent weekly entry periods.  You must enter into each weekly Entry Period separately.   How to Enter: We invite you to participate in a quest to provide "Accepted Solutions" to as many questions as you can. Answers can be provided in all the communities. Users must provide a solution which can be an “Accepted Solution” in the Forums in all of the communities and there are no limits to the number of “Accepted Solutions” that a member can provide for entries in this challenge, but each entry must be substantially unique and different.    Winner Selection and Prizes: At the end of each week, we will list the top ten (10) Community users which will consist of: 5 Community Members & 5 Super Users and they will advance to the final drawing. We will post each week in the News & Announcements the top 10 Solution providers.  At the end of the challenge, we will add all of the top 10 weekly names and enter them into a random drawing.  Then we will randomly select ten (10) winners (5 Community Members & 5 Super Users) from among all eligible entrants received across all weekly Entry Periods to receive the prize listed below. If a winner declines, we will draw again at random for the next winner.  A user will only be able to win once overall. If they are drawn multiple times, another user will be drawn at random.  Individuals will be contacted before the announcement with the opportunity to claim or deny the prize.  Once all of the winners have been notified, we will post in the News & Announcements of each community with the list of winners.   Each winner will receive one (1) Pass to the Power Platform Conference in Las Vegas, Sep. 18-20, 2024 ($1800 value). NOTE: Prize is for conference attendance only and any other costs such as airfare, lodging, transportation, and food are the sole responsibility of the winner. Tickets are not transferable to any other party or to next year’s event.   ** PLEASE SEE THE ATTACHED RULES for this CHALLENGE**   Week 1 Results: Congratulations to the Week 1 qualifiers, you are being entered in the random drawing that will take place at the end of the challenge.   Community MembersNumber SolutionsSuper UsersNumber Solutions Deenuji 9 @NathanAlvares24  17 @Anil_g  7 @ManishSolanki  13 @eetuRobo  5 @David_MA  10 @VishnuReddy1997  5 @SpongYe  9JhonatanOB19932 (tie) @Nived_Nambiar  8 @maltie  2 (tie)   @PA-Noob  2 (tie)   @LukeMcG  2 (tie)   @tgut03  2 (tie)       Week 2 Results: Congratulations to the Week 2 qualifiers, you are being entered in the random drawing that will take place at the end of the challenge. Week 2: Community MembersSolutionsSuper UsersSolutionsPower Automate  @Deenuji  12@ManishSolanki 19 @Anil_g  10 @NathanAlvares24  17 @VishnuReddy1997  6 @Expiscornovus  10 @Tjan  5 @Nived_Nambiar  10 @eetuRobo  3 @SudeepGhatakNZ 8     Week 3 Results: Congratulations to the Week 3 qualifiers, you are being entered in the random drawing that will take place at the end of the challenge. Week 3:Community MembersSolutionsSuper UsersSolutionsPower Automate Deenuji32ManishSolanki55VishnuReddy199724NathanAlvares2444Anil_g22SudeepGhatakNZ40eetuRobo18Nived_Nambiar28Tjan8David_MA22   Week 4 Results: Congratulations to the Week 4 qualifiers, you are being entered in the random drawing that will take place at the end of the challenge. Week 4:Community MembersSolutionsSuper UsersSolutionsPower Automate Deenuji11FLMike31Sayan11ManishSolanki16VishnuReddy199710creativeopinion14Akshansh-Sharma3SudeepGhatakNZ7claudiovc2CFernandes5 misc2Nived_Nambiar5 Usernametwice232rzaneti5 eetuRobo2   Anil_g2   SharonS2  

Check Out | 2024 Release Wave 2 Plans for Microsoft Dynamics 365 and Microsoft Power Platform

On July 16, 2024, we published the 2024 release wave 2 plans for Microsoft Dynamics 365 and Microsoft Power Platform. These plans are a compilation of the new capabilities planned to be released between October 2024 to March 2025. This release introduces a wealth of new features designed to enhance customer understanding and improve overall user experience, showcasing our dedication to driving digital transformation for our customers and partners.    The upcoming wave is centered around utilizing advanced AI and Microsoft Copilot technologies to enhance user productivity and streamline operations across diverse business applications. These enhancements include intelligent automation, AI-powered insights, and immersive user experiences that are designed to break down barriers between data, insights, and individuals. Watch a summary of the release highlights.    Discover the latest features that empower organizations to operate more efficiently and adaptively. From AI-driven sales insights and customer service enhancements to predictive analytics in supply chain management and autonomous financial processes, the new capabilities enable businesses to proactively address challenges and capitalize on opportunities.    

Updates to Transitions in the Power Platform Communities

We're embarking on a journey to enhance your experience by transitioning to a new community platform. Our team has been diligently working to create a fresh community site, leveraging the very Dynamics 365 and Power Platform tools our community advocates for.  We started this journey with transitioning Copilot Studio forums and blogs in June. The move marks the beginning of a new chapter, and we're eager for you to be a part of it. The rest of the Power Platform product sites will be moving over this summer.   Stay tuned for more updates as we get closer to the launch. We can't wait to welcome you to our new community space, designed with you in mind. Let's connect, learn, and grow together.   Here's to new beginnings and endless possibilities!   If you have any questions, observations or concerns throughout this process please go to https://aka.ms/PPCommSupport.   To stay up to date on the latest details of this migration and other important Community updates subscribe to our News and Announcements forums: Copilot Studio, Power Apps, Power Automate, Power Pages

Users online (1,812)