Extracting postcode from json

Hi,

I am working on a workflow to extract certain elements from an email. I have successfully used the replace function with regex for some elements of the workflow.

I however need to extract a string (UK postcode) from the email subject and I am struggling. The code is as follows:

let postcode = $node["Gmail"].json["headers"]["subject"];
items[0].json.postcode = postcode.match (/^[A-Z]{1,2}[0-9]{1,2} ?[0-9][A-Z]{2}(GIR 0AA)|((([ABCDEFGHIJKLMNOPRSTUWYZ][0-9][0-9]?)|(([ABCDEFGHIJKLMNOPRSTUWYZ][ABCDEFGHKLMNOPQRSTUVWXY][0-9][0-9]?)|(([ABCDEFGHIJKLMNOPRSTUWYZ][0-9][ABCDEFGHJKSTUW])|([ABCDEFGHIJKLMNOPRSTUWYZ][ABCDEFGHKLMNOPQRSTUVWXY][0-9][ABEHMNPRVWXY])))) [0-9][ABDEFGHJLNPQRSTUWXYZ]{2})/);
return items;

The response is allways null. However if I replace the first line with:

let postcode = “London W4 6TH”;

Then it works fine and the regex I know is fine as it is from an online source. However the postcode string is not found in the json despite it being there in the email headers

Any help gratefully received!

Welcome to the community @jppanchaud!

I created the following example workflow and it returns for me the expected result:

So if the Gmail node returns only one email (as your code only works for exactly one) and that email has the subject line “London W4 6TH” it should work exactly the same.

Hi Jan,

Thank you very much, that’s great!

I have one issue remaining… If I fetch more than one email (Gmail->GetAll->Limit=5) then this code works fine on the first email’s subject. However if there is more than one email, the code does not recognise the postcode in the other email subject. Is there a way to do this?

@jppanchaud change the function node code to:

const results = [];

for (const item of items) {
  results.push({
    json: {
      postcode: item.json.headers.subject.match(/^[A-Z]{1,2}[0-9]{1,2} ?[0-9][A-Z]{2}(GIR 0AA)|((([ABCDEFGHIJKLMNOPRSTUWYZ][0-9][0-9]?)|(([ABCDEFGHIJKLMNOPRSTUWYZ][ABCDEFGHKLMNOPQRSTUVWXY][0-9][0-9]?)|(([ABCDEFGHIJKLMNOPRSTUWYZ][0-9][ABCDEFGHJKSTUW])|([ABCDEFGHIJKLMNOPRSTUWYZ][ABCDEFGHKLMNOPQRSTUVWXY][0-9][ABEHMNPRVWXY])))) [0-9][ABDEFGHJLNPQRSTUWXYZ]{2})/)
    }
  })
}

return results;
1 Like

Amazing, thank you so much! I am getting there and slowly learning :slight_smile:

1 Like