jsonnode.jsimapemail-parsing

Parsing IMAP + mailparser return object into a JSON


I am using node's IMAP & Mailparser modules for this.

My mailbox reader function has this line that parses the header:

var parsed_header = inspect(Imap.parseHeader(buffer));

This will then return:

{ from: [ 'user <user@mail.com>' ],
subject: [ 'Test' ] }

I want to be able to parse this into a JSON using JSON.parse, but because there is no quotes around the keys + the keys are all in lists, could this be done?


Solution

  • I solved the same problem with two regex replacements:

    var header = inspect(Imap.parseHeader(buffer)).replace(/'/g,'"').replace(/([a-z]+)(: ?[\[\n])/g, '"$1"$2');
    var headerObj = JSON.parse(header);
    

    The first one replaces single quotes with double quotes, the second adds quotes around the field names.