cancel
Showing results for 
Search instead for 
Did you mean: 
Reply
Dlabar
MVP

Cleanest way to turn JS string into Dictionary collection?

I'm trying to turn any JS into a "dictionary" collection in Canvas Apps without using an external services.  To make life a little easier, let's assume that the following "constraints" are true of the JS String:

  1. It's not nested,  i.e. { "a": { "nested": "something" } } wouldn't happen, only { "a": "something", "notNested: "else" }
  2. There are no commas, double quotes, or curly braces in any strings.  So no { "a", "St Louis, MI" } or { "a": "{TODAY}"} or { "a": "she said ""No!""" }
  3. Even if the values are numbers, they are always just converted to strings
  4. It's OK to skip trailing spaces.  i.e. { "a": "Two " } and { "a": "Two" } would be equivalent

This is what I've come up with:

Clear(JsonDictionary);
ForAll(Split(Substitute(Substitute(Substitute("{""2"": 800, ""3"": 1150, ""4"": 1150}", "{", ""), "}", ""), """", ""), ","),
    Collect(JsonDictionary, {
        key: TrimEnds(First(Split(Result, ":")).Result),
        value: TrimEnds(Last(Split(Result, ":")).Result)
    });
);

 

Just curios if there are cleaner/clear methods out there, or maybe similar methods that don't have as many "constraints".

 

 

 

 

2 ACCEPTED SOLUTIONS

Accepted Solutions
Rambling-Reece
Frequent Visitor

RegEx is my preference for this as the source JSON text sounds like it is relatively simple. 

 

ClearCollect(JsonDictionary,MatchAll(TextInput1.Text,"(?:"")(?<key>[^""]*)""\s*:\s*""(?<value>[^""]*)"""))

 

The benefit to this is for the values it doesn't matter what they are as long as they do not have double quotes and it will ignore whitespace by default. 

 

The resulting table is not cleaned of the MatchAll results but instead simply adds the key and value columns for your use. I am no canvas expert so I expect there is more that can be done with the table and parsing it but this works well I guess.

 

2020-02-19 12_34_15-Clipboard.png

View solution in original post

Quick update as the solution also needs to handle integers so the following JSON text should be parsed:

 

{
    "2": "8002",
    "tt": 12345,
    "3": "1150",
    "4": "text",
    "t": 1223
}

Updated solution is:

ClearCollect(JsonDictionary,MatchAll(JsonText,"""(?<key>[^""]+)""\s*:\s*""{0,1}(?<value>[^""|,|}|\n]*)"))

 And the breakdown of the regex is, hopefully it makes sense and you can follow along.

 

Using a named group(?<key>), start the match at double quote ""(escaped for PowerApp). Match any character until the next double quote[^""] and the match must be 1 or more characters (+). The match ends with the double quote, this is here because [^""] ignores the quotes in the grouping but we still need it to continue.

""(?<key>[^""]+)""

Match 0 or more whitespace a single : and then 0 or more whitespace again. We only really want to capture the key-value pair so we do not group this at all.

                  \s*:\s*

This final part is a little more verbose but is basically doing the same as the key grouping, the difference here is we care if the text is enclosed in double quotes OR NOT. Since we do not have the quotes to end the grouping we look for either double quotes, comma, right curly bracket or a newline [^""|,|}|\n] these can all terminate the value.

                         ""{0,1}(?<value>[^""|,|}|\n]*)

 

View solution in original post

9 REPLIES 9
EricLott
Super User
Super User

When you say "without using an external services", is that referring to Power Automate? It has this built in and can return a collection to PowerApps.

Alternatively, just to verify, this is the JSON schema you would expect?

 

{
"Name": "TestName",
"Value": "ValueTest"
}

 

Also, are you generating the JSON, if not what is the source of the JSON?

 

Sidenote, this feature just got moved to "Under Review" three weeks ago in the ideas forum

https://powerusers.microsoft.com/t5/Power-Apps-Ideas/Parse-JSON-in-PowerApps/idi-p/359563

Think offline scenario @EricLott  where you don't want to be doing any external calls to something Power Automate.  

 

The JSON source in my case is just a simple setting JSON that exists in my CDS system, unlikely to change for years, but just wanted to know for my own knowledge, for the next time I need this functionality.

Got it! Here's how I would go about it.

Example JSON string (In the below examples, this will be TextInput5.Text):

 

{
"ID": 12345,
"FirstName": "Eric",
"LastName": "Lott"
}

 

Docs for the Match() function: https://docs.microsoft.com/en-us/powerapps/maker/canvas-apps/functions/function-ismatch

Extracting the ID value:

 

First(Match(TextInput5.Text,"ID"": (.+),",MatchOptions.Contains).SubMatches).Value

 

The ID value is an integer, so we want want to collect all characters between 'ID": ' and the next comma, which in regex looks like this, where (.+) signifies "return all text here":

 

ID": (.+),

 

Unfortunately the Match() function does not allow you to dynamically change your regex string, so we'd collect these values like this:

 

Clear(jsonCollection);
Collect(jsonCollection,{Name:"ID",Value:First(Match(TextInput5.Text,"ID"": (.+),",MatchOptions.Contains).SubMatches).Value});
Collect(jsonCollection,{Name:"FirstName",Value:First(Match(TextInput5.Text,"FirstName"": ""(.+)""",MatchOptions.Contains).SubMatches).Value});
Collect(jsonCollection,{Name:"LastName",Value:First(Match(TextInput5.Text,"LastName"": ""(.+)""",MatchOptions.Contains).SubMatches).Value});

 

I'm basically searching the JSON string for the standard JSON pattern and returning the value associated with it.

If this doesn't solve your problem exactly, please send a sample JSON string and I'll help further.

Here is a sample app where I do this same method to collect data from a drivers licence barcode, if you'd like to check it out.

https://powerusers.microsoft.com/t5/Community-App-Samples/Drivers-License-PDF417-Barcode-Data-Extrac... 

---
If this answered your question, please click "Accept Solution". If this helped, please Thumbs Up.

I see your solution as not any easier to read, and requiring hard coded parsing which is not desirable at all.  If they add an additional property, I have to updating the code to parse the JSON which I don't want to do.  

 

A valid solution, but not any cleaner and much more costly to maintain than mine, so I'll keep seeing if there is a simpler/better solution I guess.

Rambling-Reece
Frequent Visitor

RegEx is my preference for this as the source JSON text sounds like it is relatively simple. 

 

ClearCollect(JsonDictionary,MatchAll(TextInput1.Text,"(?:"")(?<key>[^""]*)""\s*:\s*""(?<value>[^""]*)"""))

 

The benefit to this is for the values it doesn't matter what they are as long as they do not have double quotes and it will ignore whitespace by default. 

 

The resulting table is not cleaned of the MatchAll results but instead simply adds the key and value columns for your use. I am no canvas expert so I expect there is more that can be done with the table and parsing it but this works well I guess.

 

2020-02-19 12_34_15-Clipboard.png

View solution in original post

A simple ShowColumns call would remove the other columns if so desired.  Thanks for sharing!

@Rambling-Reece 

Great solution! That doesn't require the ForAll() function, so this could go directly into an Items property if you dropped the ClearCollect().

 

Quick update as the solution also needs to handle integers so the following JSON text should be parsed:

 

{
    "2": "8002",
    "tt": 12345,
    "3": "1150",
    "4": "text",
    "t": 1223
}

Updated solution is:

ClearCollect(JsonDictionary,MatchAll(JsonText,"""(?<key>[^""]+)""\s*:\s*""{0,1}(?<value>[^""|,|}|\n]*)"))

 And the breakdown of the regex is, hopefully it makes sense and you can follow along.

 

Using a named group(?<key>), start the match at double quote ""(escaped for PowerApp). Match any character until the next double quote[^""] and the match must be 1 or more characters (+). The match ends with the double quote, this is here because [^""] ignores the quotes in the grouping but we still need it to continue.

""(?<key>[^""]+)""

Match 0 or more whitespace a single : and then 0 or more whitespace again. We only really want to capture the key-value pair so we do not group this at all.

                  \s*:\s*

This final part is a little more verbose but is basically doing the same as the key grouping, the difference here is we care if the text is enclosed in double quotes OR NOT. Since we do not have the quotes to end the grouping we look for either double quotes, comma, right curly bracket or a newline [^""|,|}|\n] these can all terminate the value.

                         ""{0,1}(?<value>[^""|,|}|\n]*)

 

View solution in original post

rajyraman
MVP

I just want to post this alternate solution for completeness. I am also attaching my sample app.image.png

Helpful resources

Announcements
PA User Group

Welcome to the User Group Public Preview

Check out new user group experience and if you are a leader please create your group

secondImage

Demo Extravaganza is Back!

We are excited to announce that Demo Extravaganza for 2021 has started!

MBAS on Demand

Microsoft Business Applications Summit sessions

On-demand access to all the great content presented by the product teams and community members! #MSBizAppsSummit #CommunityRocks

Power Apps June 2021

June Power Apps Community Call

Don't miss the call this month on June 16th - 8a PDT

Top Solution Authors
Top Kudoed Authors
Users online (25,483)