0

Using JavaScript, how do I extract the Date, To, From, Subject and Text fields from the Gmail API's return (see below)?

It's not in the usual name-value pair, at least not how I would do it with JSON. Also, the text needs to be decoded.

{
 "id": "rthrt34t34t45g45g4",
 "threadId": "gg54tgw4y45t24f3f",
 "labelIds": [
  "SENT"
 ],
 "snippet": "Testing 1 2 3",
 "historyId": "2344",
 "payload": {
  "mimeType": "multipart/alternative",
  "filename": "",
  "headers": [
   {
    "name": "MIME-Version",
    "value": "1.0"
   },
   {
    "name": "Received",
    "value": "by 101.64.82.199 with HTTP; Wed, 18 Feb 2015 21:34:49 -0800 (PST)"
   },
   {
    "name": "Date",
    "value": "Thu, 19 Feb 2015 12:34:49 +0700"
   },
   {
    "name": "Delivered-To",
    "value": "test@test.org"
   },
   {
    "name": "Message-ID",
    "value": "<retert-_RKS0Vc-U6-V8dSma5=ertertertertf2e@mail.gmail.com>"
   },
   {
    "name": "Subject",
    "value": "testing 123"
   },
   {
    "name": "From",
    "value": "A Test <test@test.org>"
   },
   {
    "name": "To",
    "value": "test.test@test.com"
   },
   {
    "name": "Content-Type",
    "value": "multipart/alternative; boundary=egrreg34t34"
   }
  ],
  "body": {
   "size": 0
  },
  "parts": [
   {
    "partId": "0",
    "mimeType": "text/plain",
    "filename": "",
    "headers": [
     {
      "name": "Content-Type",
      "value": "text/plain; charset=UTF-8"
     }
    ],
    "body": {
     "size": 8,
     "data": "MTIzNDU2DQo="
    }
   },
   {
    "partId": "1",
    "mimeType": "text/html",
    "filename": "",
    "headers": [
     {
      "name": "Content-Type",
      "value": "text/html; charset=UTF-8"
     }
    ],
    "body": {
     "size": 29,
     "data": "PGRpdiBkaXI9Imx0ciI-MTIzNDU2PC9kaXY-DQo="
    }
   }
  ]
 },
 "sizeEstimate": 651
}
FullStack
  • 5,902
  • 4
  • 43
  • 77
  • possible duplicate of [Parse JSON in JavaScript?](http://stackoverflow.com/questions/4935632/parse-json-in-javascript) – John Mee Feb 19 '15 at 11:33
  • @John Mee, no, that question is asking to parse a JSON string. My question is asking how to extract the value from a name-value pair when they are paired up in the inconvenient way that Gmail gives it to me. – FullStack Feb 20 '15 at 05:09

2 Answers2

1

Surfing on the Internet I have found this class which describes a Generic GMail Message. You might use this to easily parse the JSON (by using any of the wide range of provided libraries).

kazbeel
  • 1,378
  • 19
  • 40
1

you can use e.g. filter function as follows:

var extractField = function(json, fieldName) {
  return json.payload.headers.filter(function(header) {
    return header.name === fieldName;
  })[0];
};
var date = extractField(response, "Date");
var subject = extractField(response, "Subject");

Does this help?

andrusieczko
  • 2,824
  • 12
  • 23