How to replace the payload from json object in mule - regex

Prepared json request like below.
[{
"type": "John",
"attributes": {
"AA": [{
"value": "1234"
}]
}
},
{
}
]
I need to replace the below one with empty i.e means blank ''.
,
{
}
Could you please provide the solution for this.
Finally It should come like below.
[{
"type": "John",
"attributes": {
"AA": [{
"value": "1234"
}]
}
}
]

This regex matches the given sequence however you would probably need to change it to accept all possibilities:
/, \n\{\W+?\}/
Just replace the match with nothing.

Do you get the response as a JSON object or as a string?
If you get the response as an object you have to stringify it before applying the replace function:
payload = JSON.parse(JSON.stringify(payload).replace(/,\{\}/, ''))
If the response you posted above is already stringified and you havenĀ“t parsed it into an object, the method is:
payload = payload.replace(/\,\s+\n\s+\{\n\s+\}/,'')

To achieve this purpose, we can use DataWeave expression whether in Transform Message or in MEL.
In this case I prefer to use it in MEL: #[dw('payload filter (sizeOf $) > 0')]

You can use the flatten operator here as given below. It should remove empty json. Also you can try replace {} with null and adding skipnullon="everywhere"
flatten payload

Related

How do I extract a string of numbers from random text in Power Automate?

I am setting up a flow to organize and save emails as PDF in a Dropbox folder. The first email that will arrive includes a 10 digit identification number which I extract along with an address. My flow creates a folder in Dropbox named in this format: 2023568684 : 123 Main St. Over a few weeks, additional emails arrive that I need to put into that folder. The subject always has a 10 digit number in it. I was building around each email and using functions like split, first, last, etc. to isolate the 10 digits ID. The problem is that there is no consistency in the subjects or bodies of the messages to be able to easily find the ID with that method. I ended up starting to build around each email format individually but there are way too many, not to mention the possibility of new senders or format changes.
My idea is to use List files in folder when a new message arrives which will create an array that I can filter to find the folder ID the message needs to be saved to. I know there is a limitation on this because of the 20 file limit but that is a different topic and question.
For now, how do I find a random 10 digit number in a randomly formatted email subject line so I can use it with the filter function?
For this requirement, you really need regex and at present, PowerAutomate doesn't support the use of regex expressions but the good news is that it looks like it's coming ...
https://powerusers.microsoft.com/t5/Power-Automate-Ideas/Support-for-regex-either-in-conditions-or-as-an-action-with/idi-p/24768
There is a connector but it looks like it's not free ...
https://plumsail.com/actions/request-free-license
To get around it for now, my suggestion would be to create a function app in Azure and let it do the work. This may not be your cup of tea but it will work.
I created a .NET (C#) function with the following code (straight in the portal) ...
#r "Newtonsoft.Json"
using System.Net;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Primitives;
using Newtonsoft.Json;
public static async Task<IActionResult> Run(HttpRequest req, ILogger log)
{
string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
dynamic data = JsonConvert.DeserializeObject(requestBody);
string strToSearch = System.Text.Encoding.UTF8.GetString(Convert.FromBase64String((string)data?.Text));
string regularExpression = data?.Pattern;
var matches = System.Text.RegularExpressions.Regex.Matches(strToSearch, regularExpression);
var responseString = JsonConvert.SerializeObject(matches, new JsonSerializerSettings()
{
ReferenceLoopHandling = ReferenceLoopHandling.Ignore
});
return new ContentResult()
{
ContentType = "application/json",
Content = responseString
};
}
Then in PowerAutomate, call the HTTP action passing in a base64 encoded string of the content you want to search ...
The is the expression in the JSON ... base64(variables('String to Search')) ... and this is the json you need to pass in ...
{
"Text": "#{base64(variables('String to Search'))}",
"Pattern": "[0-9]{10}"
}
This is an example of the response ...
[
{
"Groups": {},
"Success": true,
"Name": "0",
"Captures": [],
"Index": 33,
"Length": 10,
"Value": "2023568684"
},
{
"Groups": {},
"Success": true,
"Name": "0",
"Captures": [],
"Index": 98,
"Length": 10,
"Value": "8384468684"
}
]
Next, add a Parse JSON action and use this schema ...
{
"type": "array",
"items": {
"type": "object",
"properties": {
"Groups": {
"type": "object",
"properties": {}
},
"Success": {
"type": "boolean"
},
"Name": {
"type": "string"
},
"Captures": {
"type": "array"
},
"Index": {
"type": "integer"
},
"Length": {
"type": "integer"
},
"Value": {
"type": "string"
}
},
"required": [
"Groups",
"Success",
"Name",
"Captures",
"Index",
"Length",
"Value"
]
}
}
Finally, extract the first value that you find which matches the regex pattern. It returns multiple results if found so if you need to, you can do something with those.
This is the expression ... #{first(body('Parse_JSON'))?['value']}
From this string ...
We're going to search for string 2023568684 within this text and we're also going to try and find 8384468684, this should work.
... this is the result ...
Don't have a Premium PowerAutomate licence so can't use the HTTP action?
You can do this exact same thing using the LogicApps service in Azure. It's the same engine with some slight differences re: connectors and behaviour.
Instead of the HTTP, use the Azure Functions action.
In relation to your action to fire when an email is received, in LogicApps, it will poll every x seconds/minutes/hours/etc. rather than fire on event. I'm not 100% sure which email connector you're using but it should exist.
Dropbox connectors exist, that's no problem.
You can export your PowerAutomate flow into a LogicApps format so you don't have to start from scratch.
https://learn.microsoft.com/en-us/azure/logic-apps/export-from-microsoft-flow-logic-app-template
If you're concerned about cost, don't be. Just make sure you use the consumption plan. Costs only really rack up for these services when the apps run for minutes at a time on a regular basis. Just keep an eye on it for your own mental health.
TO get the function URL, you can find it in the function itself. You have to be in the function ...

Postman Variables

I am trying to parse "Id" from below json to store it in a variable
{
"cf35864e-944d-11e9-8aff-22000ab8d684": {
"Id": "1a45b704-944e-11e9-8aff-22000ab8d684",
"Name": "Test plan",
"Type": "Limited",
"Credits": 10119.70,
"AvailableCredits": 500.100
}
}
I've tried
bodydata =JSON.parse(responseBody)
planid=bodydata.cf35864e-944d-11e9-8aff-22000ab8d684.Id
console.log(planid)
But postman throws errors, is there any way so that only ID can be fetched.
This should work: planid=bodydata["cf35864e-944d-11e9-8aff-22000ab8d684"]['Id']
As per your mentioned JSON data, the below may work.
let resp = pm.response.json();
console.log(resp.cf35864e-944d-11e9-8aff-22000ab8d684.Id);
Above will work only if "cf35864e-944d-11e9-8aff-22000ab8d684" value is static and only one object is returned.

Regex In body of API test

I'm testing API with https://cloud.google.com/datastore/docs/reference/data/rest/v1/projects/lookup
The following brings a found result with data. I would like to use a regular expression with bring back all records with name having the number 100867. All my attempts result wit a missing result set.
i.e. change to "name": "/1000867.*/"
{
"keys": [
{
"path": [
{
"kind": "Job",
"name": "1000867:100071805:1"
}
]
}
]
}
The Google documentation for lookup key states that the name is a "string" and that
The name of the entity. A name matching regex __.*__ is reserved/read-only. A name must not be more than 1500 bytes when UTF-8 encoded. Cannot be "".
The regex part threw me off and the solution was to use runQuery!
Consider this closed.

Regex working with calculator but not with AWS lambda function

Trouble with regex and gather all data between [ and ].
Testing with the program: http://regexr.com/
String data
{
"Items": [
{
"UserID": "1487840267893246",
"Timestamp": 1487204364877,
},
{
"UserID": "1487840267893336",
"Timestamp": 1487204364888,
}
],
"Count": 2,
"ScannedCount": 3
}
The below (fired in AWS lambda) has the intention of pulling all chars between the [ and ] and outputting it. (\[[^]*\]) works with the regex calc above, but only returns "undefined" in Lambda. Why?
Items = data.match(/"(\[[^]*\])"/);
console.log(Items);
An alternative solution was to extract the data into an array as follows
userID = data.match(/"UserID":"([^"]+)"/g);
console.log(userID);
Try the dotall flag:
Items = data.match(/"(?s)\[.*\]");
And you didn't need those brackets.

Extract multiple strings using Regex jmeter

I have the following JSON response.
{ "Customer1": { "details": { "acc": { "number": "91422915166" }, "phone": { "number": "98400915180" } }, "DateofBirth": "1979-04-03", "firstName": "Harry", "lastName": "Potter" } }
Jmeter script structure:
Thread group (Get customer details)
+Regular expression extractor
.....name: customer
.....expression:"number":(.+?)"DateofBirth":"(.+?)"
.....MatchNo: -1
I want to use an extractor expression that only extracts the Phone "number". My present code is extracting both acc "number" and phone "number". Can you please tell me what expression I need to use in order to get this working? Thank you
If I understand correctly, the first number in your response is account number. You don't want that. If so
Expression : "phone": { "number": "(\d+)" }
should help.
P.S. : In your expression you also have DateofBirth in the expression. You needed only the number and not DateofBirth. If you want to extract two variables with multiple occurrences, I have tutorial exactly for that here. http://goo.gl/w3u1r