cancel
Showing results for 
Search instead for 
Did you mean: 
Reply
Highlighted
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
Highlighted
Regular Visitor

Re: Cleanest way to turn JS string into Dictionary collection?

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

Highlighted
Regular Visitor

Re: Cleanest way to turn JS string into Dictionary collection?

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
Highlighted
Super User
Super User

Re: Cleanest way to turn JS string into Dictionary collection?

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

Highlighted
MVP

Re: Cleanest way to turn JS string into Dictionary collection?

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.

Highlighted
Super User
Super User

Re: Cleanest way to turn JS string into Dictionary collection?

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.

Highlighted
MVP

Re: Cleanest way to turn JS string into Dictionary collection?

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.

Highlighted
Regular Visitor

Re: Cleanest way to turn JS string into Dictionary collection?

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

Highlighted
MVP

Re: Cleanest way to turn JS string into Dictionary collection?

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

Highlighted
Super User
Super User

Re: Cleanest way to turn JS string into Dictionary collection?

@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().

 

Highlighted
Regular Visitor

Re: Cleanest way to turn JS string into Dictionary collection?

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

Highlighted

Re: Cleanest way to turn JS string into Dictionary collection?

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

Helpful resources

Announcements
Community Conference

Power Platform Community Conference

Find your favorite faces from the community presenting at the Power Platform Community Conference!

Watch Now

Experience what’s next for Power Apps

See the latest Power Apps innovations, updates, and demos from the Microsoft Business Applications Launch Event.

Power Platform ISV Studio

Power Platform ISV Studio

ISV Studio is designed to become the go-to Power Platform destination for ISV’s to monitor & manage published applications.

secondImage

Power Platform 2020 release wave 2 plan

Features releasing from October 2020 through March 2021

Top Solution Authors
Top Kudoed Authors
Users online (6,251)