FullStack
FullStack

Reputation: 6020

How to parse JSON from Gmail API using JavaScript?

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": "[email protected]"
   },
   {
    "name": "Message-ID",
    "value": "<[email protected]>"
   },
   {
    "name": "Subject",
    "value": "testing 123"
   },
   {
    "name": "From",
    "value": "A Test <[email protected]>"
   },
   {
    "name": "To",
    "value": "[email protected]"
   },
   {
    "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
}

Upvotes: 0

Views: 1622

Answers (2)

andrusieczko
andrusieczko

Reputation: 2824

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?

Upvotes: 1

kazbeel
kazbeel

Reputation: 1436

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

Upvotes: 1

Related Questions