cancel
Showing results for 
Search instead for 
Did you mean: 
Reply
ArchieGoodwin
Advocate I
Advocate I

Extracting a substring from parsed JSON data in a Loop

I'm stumped on this one, folks.

I am taking JSON data from an online form, parsing it, and converting it into a .csv for import. I have built and tested a flow that works exactly as needed - almost. 

The online form gives users the option to enter information for anywhere from 0 to 10 children (family law intake). So, the JSON can contain data for 0 to 10 children. Incoming data for the fields contains either a six-or-eight-character Code, and then an explanation (it's in a drop-down on the online form). I need to export only a substring of that data (either the left 6 or 8 characters) into the .csv for import.

 

Problem is, I can't use Initialize Variable to do this within a loop (that will run x times, where x = 0 to 10).

Is there a way to substring just the raw parsed JSON data so I only grab the characters I need for inclusion in the variable table I have created for the data (prior to export to .csv)? I have tried to use the 'substring' expression, but it won't even let me select the variable I need from within the sub-data for "CHILDINV" - I'm stuck.

Child Data Loop.JPG

27 REPLIES 27
ArchieGoodwin
Advocate I
Advocate I

No, we want a consistent header line, even if there is no data in the field below. Makes it easier that way.

@Paulie78 's solution looks a bit less daunting tbh, but I'm stuck on understanding how he is referencing the fields.

 

I now see that doing it the way I was doing it, via variables, is long and cumbersome - this "compose" function makes it more of a one-shot schema creation. As much as I hate to throw away what I have done already, I like that it moves all of the expressions and fiddling with the data into one place.

I have lots to learn on this stuff, it's only the first of many I am going to have to create. Thanks so much for your patience and efforts thus far.

If you need help building it reach out via private message and will get you started off.

It does produce two rows, perhaps I copied the wrong scope. Will check in a moment. 

eliotcole
Super User
Super User

Absolutely, @ArchieGoodwin, here's a solution which produces all the rows, all the headers, and the full 10 kids.

 

I'll admit that were this me I'd space out the logic a bit more so that others won't be blinded by the long expressions on show. One of the main things I try to show folks in a work environment that Power Automate makes an office less reliable on Jon/Janey and their wizard excel formulas. As soon as you start sprinkling long 'formula' everywhere here, anyone taking over the management of it might still be a bit taken aback.

 

If I were to do that here, I might make the two sides of that union in the CSV separate object variables then reference them.


Solution

This solution is transferrable if you want to apply it to more than one array in the original data.

finally.jpg

@Paulie78 thanks for the help, and for the range fiddle, too! I had originally done ten fields that long way, and thought that there *had* to be a way to get it done with less typing. 😅


Code

kidsVAR

This just counts the number of kids, and subtracts it by one. This saves overcomplicating the multiple if() statements in the Select action.

 

 

sub(length(variables('jsonInputVAR')?['body']?['CHILDINV']), 1)

 

 

SelectKidsData

In the 'From' field this uses a trick that Paulie taught me elsewhere, the range() function. So it iterates through 10 items, regardless.

 

 

range(0, 10)

 

 

In the 'Map' 'key' fields (left), this uses some basis logic looking at the current item() number in the range, and adds 1. This provides your child number.

 

 

add(item(), 1)

 

 

In the 'Map' 'value' fields (right), this uses a simple condition. If the current item() number is greater than the number returned in the kidsVAR variable, then it places nothing ('') in the field, otherwise it picks the child data that is correspondent to the current item() number. It looks like more than it is. 👍

 

 

if(greater(item(), variables('kidsVAR')), '', variables('jsonInputVAR')?['body']?['CHILDINV'][item()]['Id'])

if(greater(item(), variables('kidsVAR')), '', variables('jsonInputVAR')?['body']?['CHILDINV'][item()]['C1NAME'])

if(greater(item(), variables('kidsVAR')), '', variables('jsonInputVAR')?['body']?['CHILDINV'][item()]['C1BD'])

if(greater(item(), variables('kidsVAR')), '', variables('jsonInputVAR')?['body']?['CHILDINV'][item()]['Gender'])

if(greater(item(), variables('kidsVAR')), '', variables('jsonInputVAR')?['body']?['CHILDINV'][item()]['C1LEGAL'])

if(greater(item(), variables('kidsVAR')), '', variables('jsonInputVAR')?['body']?['CHILDINV'][item()]['C1PHYS'])

if(greater(item(), variables('kidsVAR')), '', variables('jsonInputVAR')?['body']?['CHILDINV'][item()]['C1VISIT'])

if(greater(item(), variables('kidsVAR')), '', variables('jsonInputVAR')?['body']?['CHILDINV'][item()]['FIELD8'])

if(greater(item(), variables('kidsVAR')), '', variables('jsonInputVAR')?['body']?['CHILDINV'][item()]['ItemNumber'])

 

 

Create CSV Table

This one is basically constructing an array for the Create CSV Table action to make its data from. Don't forget to place the square brackets around it in the 'From' field:

 

 

union(removeProperty(variables('jsonInputVAR')?['body'], 'CHILDINV') , json(replace(join(body('SelectKidsData'), ', '), '}, {', ',')))

 

 

The union() function is usually used to join two arrays together, but it works with objects, too, so the main thing here is ensuring that the child data is represented as an object instead of an array, after the previous Select action has done its thing.

 

So, in the second section of that union function this is done by:

  1. Using a join() function to join the separate children items together in a string value.
  2. Once they're in the string, they're still actually separated by curly brackets, so the replace() function removes the ones separating the children '}, {', and puts a normal comma in their place.
  3. Then finally the json() function makes that all readable by the union otherwise it would error thinking it's just a string.

 

The first part is getting all the non-child data by simply using the removeProperty() function to strip the CHILDINV data out of the original object.

 

Additional Arrays

To apply this to other fields in the original JSON just requires a few tweaks. Let's look at the potential for the DOCUMENTS array field to need it.

  1. Add a branch after the input.
  2. Initialise a docsVAR integer variable in the new branch to count the items in DOCUMENTS.
  3. For the Select copy the original and edit it to save time to SelectDocsData.
  4. Change the letters either side of the add(item(),1) expressions in the key fields to make your document headers.
  5. Edit each value to point to DOCUMENTS instead of CHILDINV, the new docsVAR for the counts, and change the referenced field names.
  6. Finally, bridge the branches with the CSV:

 

union(removeProperty(removeProperty(variables('jsonInputVAR')?['body'], 'CHILDINV'), 'DOCUMENTS') , json(replace(join(body('SelectKidsData'), ', '), '}, {', ',')) , json(replace(join(body('SelectDocsData'), ', '), '}, {', ',')))

 

If there is no set limit to the documents, then take the docsVAR and add 1 to it for the other side of the range() expression.

 

EDIT - I've tested this on ten children ... and they're all still alive to tell the tale!

One teeny tiny problem. I can't figure out how to put the SUBSTRING instruction into the map. I keep getting "invalid expression" errors; how do I grab only, say, the first 6 characters in C1LEGAL for example? I know it's probably a syntax issue.

Where would you squeeze in the SUBSTRING?

Also - I really only need the CHILD output from this, because I don't carry across all the fields, only ones I need. But, if I try to create a CSV table from OUTPUT, there are a bunch of extra commas in there that I don't need.

Thoughts?

eliotcole
Super User
Super User

(sorry, was weirdly scared to come back in case it wasn't a good solution!)

 

I'm glad all is good, @ArchieGoodwin  ... apologies if I'd misunderstood. But given your responses after Paulie mentioned ensuring there were 10 kids each time, I thought the extra data was what you were after there.

 

Those extra commas in the example of 4 children are the empty children 5-10. (or empty fields in the base data)

 

If you wish to have only what's there (for the kids, at least), that's more simple, just change the SelectKidsData to be like in my OG solution with the ['body']?['CHILDINV'] source, item()['ItemNumber'] for the numbered keys, and reference the fields accordingly (item()?['Id']) on the value side. You can delete the count, too.

02 - Kids Data OG.jpg

 

 

SUBSTRING

This part is thankfully easy, I'll give you two ways you can do it and hopefully the first is the way that it can be done easiest.

 

Method One - Add An Extra Select Value

This assumes that you will always have "TEXT - TEXT", meaning that there is always that space-hyphen-space, there.

 

On the 'Key' side it will be however you like, as before. I labelled mine as C3LGLSh (where the 3 is the expression).

 

On the 'Value' side it will be:

 

if(greater(item(), variables('kidsVAR')), '', first(split(variables('jsonInputVAR')?['body']?['CHILDINV'][item()]['C1LEGAL'], ' - ')))

 

You are splitting the "CLIENT - sdfkjhsfgldihsd fg" text on that ' - ', and then with the array that returns you take the first item. A safer bet might be to split on just the hypen, and then wrap the first() in a trim() expression.

 

This ensures that you are always going to get whatever text is there, even if it's longer than 6 characters.

 

Method Two - Substring

If you really have to use substring, then this would work with the otherwise same setup as the first method:

 

 

if(greater(item(), variables('kidsVAR')), '', substring(variables('jsonInputVAR')?['body']?['CHILDINV'][item()]['C1LEGAL'], 0, 6))

 

 

It definitely works, just tested, I just feel that the split+first (+trim!) method is going to be better data capture long term.

 

 

KIDS ONLY!

If you only need the CHILD output, then you can junk the union() expression and just keep the second half of it. So, non-code view thats:

[

  json(repl...)

]

In the json() you'd have:

 

json(replace(join(body('SelectKidsData'), ', '), '}, {', ','))

 

 

NONSENSE STUFFS 😉

There's a few ways to go about the unimportant fields.

  1. Filter - Filter out stuff you don't want, try to use branching if you can to keep the original data available when needed.
  2. Handle Externally - Keep the extra fields, and handle the relevant output on the other end. You then have that data when you need it.
  3. Layered Property Removal - removeProperty() layers to remove the fields you don't currently need.
  4. Explicit Select Fields - Use Paulie's setup to be very exact precisely which field and where you're taking data from.

#2 would be the most accepted/normal way. For example if you were querying an API for data, you would take what you get, and use what you need.

 

With #3 you just layer it up, like this:

 

removeProperty(removeProperty(variables('jsonInputVAR')?['body'], 'CHILDINV'), 'DOCUMENTS')

 

That would supply an object with all the original fields except the CHILDINV, and DOCUMENTS, fields. 

 

Here's one more image to assist, this one has all 10 kids included, obviously:

extra bitz.jpg

 

Helpful resources

Announcements

Power Platform Connections Ep 14 | J. Panchal | Thursday, 18 May 2023

Episode Fourteen of Power Platform Connections sees David Warner and Hugo Bernier talk to Microsoft PM Jocelyn Panchal, alongside the latest news, videos, product reviews, and community blogs.     Use the hashtag #PowerPlatformConnects on social media for a chance to have your work featured on the show.      Show schedule in this episode:  00:00 Cold Open 00:32 Show Intro 01:10 Jocelyn Panchal Interview 24:10 Blogs & Articles 29:50 Outro & Bloopers  Check out the blogs and articles featured in this week’s episode:   https://www.nathalieleenders.com/Blog/index.php/;focus=STRATP_com_cm4all_wdn_Flatpress_42136159&path=?x=entry:entry230511-101930#C_STRATP_com_cm4all_wdn_Flatpress_42136159__-anchor  @NathLeenders https://www.keithatherton.com/posts/2023-05-12-msbuild2023-cloud-skills-challenge/  @MrKeithAtherton https://elliskarim.com/2023/05/13/how-to-find-files-in-onedrive-that-match-a-naming-pattern/  @MrCaptainKarim https://www.linkedin.com/pulse/my-fond-memories-scottish-summit-2022-pranav-khurana/ @pranavkhuranauk https://www.linkedin.com/feed/update/urn:li:activity:7061777660745560064/?updateEntityUrn=urn%3Ali%3Afs_feedUpdate%3A%28V2%2Curn%3Ali%3Aactivity%3A7061777660745560064%29  @thevictordantas  Action requested: Feel free to provide feedback on how we can make our community more inclusive and diverse.  This episode premiered live on our YouTube at 12pm PST on Thursday 18th May 2023.  Video series available at Power Platform Community YouTube channel.  Upcoming events:  Power Apps Developers Summit – May 19-20th - London European Power Platform conference – Jun. 20-22nd - Dublin Microsoft Power Platform Conference – Oct. 3-5th - Las Vegas  Join our Communities:  Power Apps Community Power Automate Community Power Virtual Agents Community Power Pages Community  If you’d like to hear from a specific community member in an upcoming recording and/or have specific questions for the Power Platform Connections team, please let us know. We will do our best to address all your requests or questions.   

May 2023 Community Newsletter and Upcoming Events

Welcome to our May 2023 Community Newsletter, where we'll be highlighting the latest news, releases, upcoming events, and the great work of our members inside the Biz Apps communities. If you're new to this LinkedIn group, be sure to subscribe here in the News & Announcements to stay up to date with the latest news from our ever-growing membership network who "changed the way they thought about code".         LATEST NEWS "Mondays at Microsoft" LIVE on LinkedIn - 8am PST - Monday 15th May  - Grab your Monday morning coffee and come join Principal Program Managers Heather Cook and Karuana Gatimu for the premiere episode of "Mondays at Microsoft"! This show will kick off the launch of the new Microsoft Community LinkedIn channel and cover a whole host of hot topics from across the #PowerPlatform, #ModernWork, #Dynamics365, #AI, and everything in-between. Just click the image below to register and come join the team LIVE on Monday 15th May 2023 at 8am PST. Hope to see you there!     Executive Keynote | Microsoft Customer Success Day CVP for Business Applications & Platform, Charles Lamanna, shares the latest #BusinessApplications product enhancements and updates to help customers achieve their business outcomes.         S01E13 Power Platform Connections - 12pm PST - Thursday 11th May Episode Thirteen of Power Platform Connections sees Hugo Bernier take a deep dive into the mind of co-host David Warner II, alongside the reviewing the great work of Dennis Goedegebuure, Keith Atherton, Michael Megel, Cat Schneider, and more. Click below to subscribe and get notified, with David and Hugo LIVE in the YouTube chat from 12pm PST. And use the hashtag #PowerPlatformConnects on social media for a chance to have your work featured on the show.         UPCOMING EVENTS   European Power Platform Conference - early bird ticket sale ends! The European Power Platform Conference early bird ticket sale ends on Friday 12th May 2023! #EPPC23 brings together the Microsoft Power Platform Communities for three days of unrivaled days in-person learning, connections and inspiration, featuring three inspirational keynotes, six expert full-day tutorials, and over eighty-five specialist sessions, with guest speakers including April Dunnam, Dona Sarkar, Ilya Fainberg, Janet Robb, Daniel Laskewitz, Rui Santos, Jens Christian Schrøder, Marco Rocca, and many more. Deep dive into the latest product advancements as you hear from some of the brightest minds in the #PowerApps space. Click here to book your ticket today and save!      DynamicMinds Conference - Slovenia - 22-24th May 2023 It's not long now until the DynamicsMinds Conference, which takes place in Slovenia on 22nd - 24th May, 2023 - where brilliant minds meet, mingle & share! This great Power Platform and Dynamics 365 Conference features a whole host of amazing speakers, including the likes of Georg Glantschnig, Dona Sarkar, Tommy Skaue, Monique Hayward, Aleksandar Totovic, Rachel Profitt, Aurélien CLERE, Ana Inés Urrutia de Souza, Luca Pellegrini, Bostjan Golob, Shannon Mullins, Elena Baeva, Ivan Ficko, Guro Faller, Vivian Voss, Andrew Bibby, Tricia Sinclair, Roger Gilchrist, Sara Lagerquist, Steve Mordue, and many more. Click here: DynamicsMinds Conference for more info on what is sure an amazing community conference covering all aspects of Power Platform and beyond.    Days of Knowledge Conference in Denmark - 1-2nd June 2023 Check out 'Days of Knowledge', a Directions 4 Partners conference on 1st-2nd June in Odense, Denmark, which focuses on educating employees, sharing knowledge and upgrading Business Central professionals. This fantastic two-day conference offers a combination of training sessions and workshops - all with Business Central and related products as the main topic. There's a great list of industry experts sharing their knowledge, including Iona V., Bert Verbeek, Liza Juhlin, Douglas Romão, Carolina Edvinsson, Kim Dalsgaard Christensen, Inga Sartauskaite, Peik Bech-Andersen, Shannon Mullins, James Crowter, Mona Borksted Nielsen, Renato Fajdiga, Vivian Voss, Sven Noomen, Paulien Buskens, Andri Már Helgason, Kayleen Hannigan, Freddy Kristiansen, Signe Agerbo, Luc van Vugt, and many more. If you want to meet industry experts, gain an advantage in the SMB-market, and acquire new knowledge about Microsoft Dynamics Business Central, click here Days of Knowledge Conference in Denmark to buy your ticket today!   COMMUNITY HIGHLIGHTS Check out our top Super and Community Users reaching new levels! These hardworking members are posting, answering questions, kudos, and providing top solutions in their communities.   Power Apps:  Super Users: @WarrenBelz, @LaurensM  @BCBuizer  Community Users:  @Amik@ @mmollet, @Cr1t    Power Automate:  Super Users: @Expiscornovus , @grantjenkins, @abm  Community Users: @Nived_Nambiar, @ManishSolanki    Power Virtual Agents:  Super Users: @Pstork1, @Expiscornovus  Community Users: @JoseA, @fernandosilva, @angerfire1213    Power Pages: Super Users: @ragavanrajan  Community Users: @Fubar, @Madhankumar_L,@gospa  LATEST COMMUNITY BLOG ARTICLES  Power Apps Community Blog  Power Automate Community Blog  Power Virtual Agents Community Blog  Power Pages Community Blog  Check out 'Using the Community' for more helpful tips and information:  Power Apps , Power Automate, Power Virtual Agents, Power Pages 

Announcing | Super Users - 2023 Season 1

Super Users – 2023 Season 1    We are excited to kick off the Power Users Super User Program for 2023 - Season 1.  The Power Platform Super Users have done an amazing job in keeping the Power Platform communities helpful, accurate and responsive. We would like to send these amazing folks a big THANK YOU for their efforts.      Super User Season 1 | Contributions July 1, 2022 – December 31, 2022  Super User Season 2 | Contributions January 1, 2023 – June 30, 2023    Curious what a Super User is? Super Users are especially active community members who are eager to help others with their community questions. There are 2 Super User seasons in a year, and we monitor the community for new potential Super Users at the end of each season. Super Users are recognized in the community with both a rank name and icon next to their username, and a seasonal badge on their profile.  Power Apps  Power Automate  Power Virtual Agents  Power Pages  Pstork1*  Pstork1*  Pstork1*  OliverRodrigues  BCBuizer  Expiscornovus*  Expiscornovus*  ragavanrajan  AhmedSalih  grantjenkins  renatoromao    Mira_Ghaly*  Mira_Ghaly*      Sundeep_Malik*  Sundeep_Malik*      SudeepGhatakNZ*  SudeepGhatakNZ*      StretchFredrik*  StretchFredrik*      365-Assist*  365-Assist*      cha_cha  ekarim2020      timl  Hardesh15      iAm_ManCat  annajhaveri      SebS  Rhiassuring      LaurensM  abm      TheRobRush  Ankesh_49      WiZey  lbendlin      Nogueira1306  Kaif_Siddique      victorcp  RobElliott      dpoggemann  srduval      SBax  CFernandes      Roverandom  schwibach      Akser  CraigStewart      PowerRanger  MichaelAnnis      subsguts  David_MA      EricRegnier  edgonzales      zmansuri  GeorgiosG      ChrisPiasecki  ryule      AmDev  fchopo      phipps0218  tom_riha      theapurva  takolota     Akash17  momlo     BCLS776  Shuvam-rpa     rampprakash  ScottShearer     Rusk  ChristianAbata     cchannon  Koen5     a33ik  Heartholme     AaronKnox  okeks      Matren  David_MA     Alex_10        Jeff_Thorpe        poweractivate        Ramole        DianaBirkelbach        DavidZoon        AJ_Z        PriyankaGeethik        BrianS        StalinPonnusamy        HamidBee        CNT        Anonymous_Hippo        Anchov        KeithAtherton        alaabitar        Tolu_Victor        KRider        sperry1625        IPC_ahaas      zuurg    rubin_boer   cwebb365   Dorrinda   G1124   Gabibalaban   Manan-Malhotra   jcfDaniel   WarrenBelz   Waegemma   drrickryp   GuidoPreite   metsshan    If an * is at the end of a user's name this means they are a Multi Super User, in more than one community. Please note this is not the final list, as we are pending a few acceptances.  Once they are received the list will be updated. 

Check out the new Power Platform Communities Front Door Experience!

We are excited to share the ‘Power Platform Communities Front Door’ experience with you!   Front Door brings together content from all the Power Platform communities into a single place for our community members, customers and low-code, no-code enthusiasts to learn, share and engage with peers, advocates, community program managers and our product team members. There are a host of features and new capabilities now available on Power Platform Communities Front Door to make content more discoverable for all power product community users which includes ForumsUser GroupsEventsCommunity highlightsCommunity by numbersLinks to all communities Users can see top discussions from across all the Power Platform communities and easily navigate to the latest or trending posts for further interaction. Additionally, they can filter to individual products as well.   Users can filter and browse the user group events from all power platform products with feature parity to existing community user group experience and added filtering capabilities.     Users can now explore user groups on the Power Platform Front Door landing page with capability to view all products in Power Platform.      Explore Power Platform Communities Front Door today. Visit Power Platform Community Front door to easily navigate to the different product communities, view a roll up of user groups, events and forums.

Microsoft Power Platform Conference | Registration Open | Oct. 3-5 2023

We are so excited to see you for the Microsoft Power Platform Conference in Las Vegas October 3-5 2023! But first, let's take a look back at some fun moments and the best community in tech from MPPC 2022 in Orlando, Florida.   Featuring guest speakers such as Charles Lamanna, Heather Cook, Julie Strauss, Nirav Shah, Ryan Cunningham, Sangya Singh, Stephen Siciliano, Hugo Bernier and many more.   Register today: https://www.powerplatformconf.com/   

Users online (4,757)