NodeJS: retrieving an array which is wrapped in a string - javascript

I'm currently trying to save a mail object () I'm getting back from an API into our Mongo database.
This is all fine for all values being passed accept the field 'attachments'. The attachments are supposed to be an array of objects, but this is wrapped in a string. My question now is: how do I get the array out of that string?
Example of the req.body which I'm getting from the POST request:
{ timestamp: '1538728432', token:
'0a1336769443d5a593d0ef7c1c817d29ef64ba422fc3cc45f1', signature:
'c44c67660f0ad97bbb5ece92c733302d4511d4607b5787ae6aa8f2203b0e2e3e',
domain: 'karaton.uk', From: '',
'X-Envelope-From': '', To: '',
'Dkim-Signature': 'v=1; a=rsa-sha256;
c=relaxed/relaxed;\td=karaton.be;
s=20140924;\th=content-type:subject:reply-to:from:to:message-id:mime-version:date:from;\tbh=Xfm+LiX4NVMKTRaQB7gNUXf6z8yVjUqn23aenMee/q4=;\tb=JEslFgXEsO3/kW3khZFF6F4HEo9Mwx+oXJH5DGsXALaGa98ki9o5tLddmEcClqhZ8IJLR0+vrMJ3x\t
zU5ThqHNElHpt6VE9MX5ZSHJHnI2kiEXq7MN5BUWfStlS2stYwooZcuZKOkbZXRaUHODewUQbhvZQD\t
5/eA5RltbAOqwIaA=', from: '', 'User-Agent':
'One.com webmail 27.8.5', Date: 'Fri, 05 Oct 2018 10:21:49 +0200',
'Message-Id': '<1538727709180.51726.8212#webmail12>',
'Mime-Version': '1.0', Received: [ 'from
mailrelay4-2.pub.mailoutpod1-cph3.one.com
(mailrelay4-2.pub.mailoutpod1-cph3.one.com [46.30.212.3]) by
mxa.mailgun.org with ESMTP id 5bb71f1f.7f030c2a1580-smtp-in-n02; Fri,
05 Oct 2018 08:21:51 -0000 (UTC)',
'from onecom-webmail2 94.143.189.242 (unknown [46.30.211.130])\tby mailrelay4.pub.mailoutpod1-cph3.one.com (Halon)
with ESMTPSA\tid b4d6415f-c877-11e8-86b7-d0431ea8bb10;\tFri, 05 Oct
2018 08:21:49 +0000 (UTC)' ], 'X-Halone-Cookie':
'c9ea0f7e80128b5bfaf5bf8d8aca6fced5bcb162', subject: '2
attachments', 'message-url':
'https://se.api.mailgun.net/v3/domains/karaton.uk/messages/eyJwIjpmYWxzZSwiayI6IjEyNzQ1ZmViLTM4OTItNDdkZC04MTJiLWJlYzU4ZjNjYTI4MCIsInMiOiI1NDE1ODQ0ZjIyIiwiYyI6InRhbmtiIn0=',
'Reply-To': '', recipient: 'tho#karaton.uk',
sender: 'thomas.l#karaton.be', 'X-Mailgun-Incoming': 'Yes',
'message-headers': '[["X-Mailgun-Incoming", "Yes"],
["X-Envelope-From", ""], ["Received", "from
mailrelay4-2.pub.mailoutpod1-cph3.one.com
(mailrelay4-2.pub.mailoutpod1-cph3.one.com [46.30.212.3]) by
mxa.mailgun.org with ESMTP id 5bb71f1f.7f030c2a1580-smtp-in-n02; Fri,
05 Oct 2018 08:21:51 -0000 (UTC)"], ["Dkim-Signature", "v=1;
a=rsa-sha256; c=relaxed/relaxed;\td=karaton.be;
s=20140924;\th=content-type:subject:reply-to:from:to:message-id:mime-version:date:from;\tbh=Xfm+LiX4NVMKTRaQB7gNUXf6z8yVjUqn23aenMee/q4=;\tb=JEslFgXEsO3/kW3khZFF6F4HEo9Mwx+oXJH5DGsXALaGa98ki9o5tLddmEcClqhZ8IJLR0+vrMJ3x\t
zU5ThqHNElHpt6VE9MX5ZSHJHnI2kiEXq7MN5BUWfStlS2stYwooZcuZKOkbZXRaUHODewUQbhvZQD\t
5/eA5RltbAOqwIaA="], ["X-Halone-Cookie",
"c9ea0f7e80128b5bfaf5bf8d8aca6fced5bcb162"], ["X-Halone-Id",
"b4d6415f-c877-11e8-86b7-d0431ea8bb10"], ["Received", "from
onecom-webmail2 94.143.189.242 (unknown [46.30.211.130])\tby
mailrelay4.pub.mailoutpod1-cph3.one.com (Halon) with ESMTPSA\tid
b4d6415f-c877-11e8-86b7-d0431ea8bb10;\tFri, 05 Oct 2018 08:21:49
+0000 (UTC)"], ["X-Originating-Ip", "94.143.189.242"], ["User-Agent", "One.com webmail 27.8.5"], ["Date", "Fri, 05 Oct 2018 10:21:49
+0200"], ["Mime-Version", "1.0"], ["Message-Id", "<1538727709180.51726.8212#webmail12>"], ["To", ""],
["From", ""], ["Reply-To",
""], ["Subject", "2 attachments"],
["Content-Type", "multipart/mixed;
boundary=\"----------8210-1538727709180-1\""]]', 'X-Halone-Id':
'b4d6415f-c877-11e8-86b7-d0431ea8bb10', 'Content-Type':
'multipart/mixed; boundary="----------8210-1538727709180-1"',
'X-Originating-Ip': '94.143.189.242', Subject: '2 attachments',
attachments: '[{"url":
"https://se.api.mailgun.net/v3/domains/karaton.uk/messages/eyJwIjpmYWxzZSwiayI6IjEyNzQ1ZmViLTM4OTItNDdkZC04MTJiLWJlYzU4ZjNjYTI4MCIsInMiOiI1NDE1ODQ0ZjIyIiwiYyI6InRhbmtiIn0=/attachments/0",
"content-type": "application/pdf", "name": "WOORDZOEKER maken _ Online
_ Met oplossing2 copy.pdf", "size": 53398}, {"url": "https://se.api.mailgun.net/v3/domains/karaton.uk/messages/eyJwIjpmYWxzZSwiayI6IjEyNzQ1ZmViLTM4OTItNDdkZC04MTJiLWJlYzU4ZjNjYTI4MCIsInMiOiI1NDE1ODQ0ZjIyIiwiYyI6InRhbmtiIn0=/attachments/1",
"content-type":
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
"name": "Geschatte uren.xlsx", "size": 44210}]', 'body-plain':
'\r\n\r\n', 'body-html': '\r\n', 'stripped-html':
'\n', 'stripped-text': '', 'stripped-signature': ''
}

Use the built-in JSON.parse() function, it'll return an array of objects as it should. It's opposed to JSON.stringify(), which does the opposite. So, basically,
JSON.parse(req.body.attachments) should do the trick.

JSON.parse should do the trick
const response = {
timestamp: '1538728432',
token: '0a1336769443d5a593d0ef7c1c817d29ef64ba422fc3cc45f1',
Subject: '2 attachments',
attachments: '[{"url": "https://se.api.mailgun.net/v3/domains/karaton.uk/messages/eyJwIjpmYWxzZSwiayI6IjEyNzQ1ZmViLTM4OTItNDdkZC04MTJiLWJlYzU4ZjNjYTI4MCIsInMiOiI1NDE1ODQ0ZjIyIiwiYyI6InRhbmtiIn0=/attachments/0", "content-type": "application/pdf", "name": "WOORDZOEKER maken _ Online _ Met oplossing2 copy.pdf", "size": 53398}, {"url": "https://se.api.mailgun.net/v3/domains/karaton.uk/messages/eyJwIjpmYWxzZSwiayI6IjEyNzQ1ZmViLTM4OTItNDdkZC04MTJiLWJlYzU4ZjNjYTI4MCIsInMiOiI1NDE1ODQ0ZjIyIiwiYyI6InRhbmtiIn0=/attachments/1", "content-type": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "name": "Geschatte uren.xlsx", "size": 44210}]'
}
const attachments = JSON.parse(response.attachments);
console.log(attachments[0]);
console.log(attachments[1]);
Ref:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse

Related

How to extract a value from a JSON document with JS

i´n very new working with JSON, and JS, so i got a problem, I´m trying to get the value inside the object attachments[{path = "..."}], but i get multiple errors due I don´t really know how to do it.
This is my JSON:
[{ "from": [{ "address": "luis#gmail.com", "name": "Luis " }], "date": "2022-06-16T14:01:08.000Z", "receivedDate": "2022-06-16T14:01:26.000Z", "to": [{ "address": "luis.#ton.edu.co", "name": "" }], "subject": "Facturacion electronica", "text": "\n", "textPlain": "\n", "hasAttachment": true, "original": { "body": "<meta http-equiv=\"content-type\" content=\"text/html; charset=utf-8\" /><div dir=\"ltr\"><div class=\"gmail_default\" style=\"font-family:arial,helvetica,sans-serif;font-size:large\"><br></div></div>\n", "headers": { "received": ["from DM5PR1301MB2218.namprd13.prod.outlook.com (2603:10b6:4:30::30) by MN2PR13MB3693.namprd13.prod.outlook.com with HTTPS; Thu, 16 Jun 2022 14:01:26 +0000", "from SN4PR0201CA0046.namprd02.prod.outlook.com (2603:10b6:803:2e::32) by DM5PR1301MB2218.namprd13.prod.outlook.com (2603:10b6:4:30::30) with Microsoft SMTP Server (version=TLS1_2, cipher=TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384) id 15.20.5353.11; Thu, 16 Jun 2022 14:01:23 +0000", "from SN1NAM02FT0046.eop-nam02.prod.protection.outlook.com (2603:10b6:803:2e:cafe::73) by SN4PR0201CA0046.outlook.office365.com (2603:10b6:803:2e::32) with Microsoft SMTP Server (version=TLS1_2, cipher=TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384) id 15.20.5353.14 via Frontend Transport; Thu, 16 Jun 2022 14:01:23 +0000", "from mail-pg1-f182.google.com (209.85.215.182) by SN1NAM02FT0046.mail.protection.outlook.com (10.97.5.4) with Microsoft SMTP Server (version=TLS1_2, cipher=TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384) id 15.20.5353.14 via Frontend Transport; Thu, 16 Jun 2022 14:01:22 +0000", "by mail-pg1-f182.google.com with SMTP id d129so1314505pgc.9 for <luis.villalba.9677#miremington.edu.co>; Thu, 16 Jun 2022 07:01:22 -0700 (PDT)"], "authentication-results": "spf=pass (sender IP is 209.85.215.182) smtp.mailfrom=gmail.com; dkim=pass (signature was verified) header.d=gmail.com;dmarc=pass action=none header.from=gmail.com;compauth=pass reason=100", "received-spf": "Pass (protection.outlook.com: domain of gmail.com designates 209.85.215.182 as permitted sender) receiver=protection.outlook.com; client-ip=209.85.215.182; helo=mail-pg1-f182.google.com; pr=C", "dkim-signature": "v=1; a=rsa-sha256; c=relaxed/relaxed; d=gmail.com; s=20210112; h=mime-version:from:date:message-id:subject:to; bh=vQCl0MdNDi0YVPYmwIcLob2sZQ71Mebd3Yrxzhr2nV8=; b=hOasXO3PARCRh6q+OUeBy9jgqQMeCXFnFtqECYaqBHWLIMMEhmsEASC3TgBGD/e2aT ssZZWLPMebxtvH/MlywEDSpAT7XIaEPdng94OXrUeIFc3LeGwxc9XYpVqM4AYn3fIGko cxP9anbIq+X4a0wP5h8QZha4lR4ljPlsVFwk9vNMeEsjxcvdpeUR0wgFo2S5jLYx6dIp UoNKHM5+jtcYLvIozU9Jyo0SjZhTy6HjEQGBgLCq2qgliCsrJdr2U2jg1KvMfgCwe/ML sfsyCxxicz3k5vd7alNEui1sbCEvNw8NnKjOyuXygKQo3DOvDrR3sO4DGOpjaJTMUjlt nqsA==", "x-google-dkim-signature": "v=1; a=rsa-sha256; c=relaxed/relaxed; d=1e100.net; s=20210112; h=x-gm-message-state:mime-version:from:date:message-id:subject:to; bh=vQCl0MdNDi0YVPYmwIcLob2sZQ71Mebd3Yrxzhr2nV8=; b=CDJrrRsU7P8GE+Wt91DoNru2dF7J2CBccSM7ST/dy+N7DJ3laHstwWF4qGcc/jdHXb yKDcUnA8tEH+SAlI+qMSVh2w60uyT7kVMKqMp9Pxf6oUj3ARanktSic0aZcVr/HN9kfh cu4FcU8AlUl+dSNg+dQ8fbmjvinuiMk1o2NG08HiXq9H5NQDMrss70sU7LA+yHqp0j9r +FrpsyAPlki58Kfj7MonmoqBSm9P5MCxVDRDp/N8lz0KCpMor5mXIUsb3Qb0F9YY97Ly 1Dfu31FmBSD2iVcYQ73xyEcpFNLRk22PiHHfBjmtkggRm5HvcPeqE8irblzRSP5zQoLX RAVw==", "x-gm-message-state": "AJIora+bCFuSkz5hlTY5ZdIyetiVpD0KGMzS4fcKCNGoEhA2qgQ9vp1G LtSF7qtu89FIJkcLfM3fasLPL8YL2M8KURKW5DCFUgbcurU=", "x-google-smtp-source": "AGRyM1vNXatnK7wAXbgyqbI4O/wuFK+BQ3cfP1jz3ra3mzWl/22XO5Q4YDaFGEZ4aq0pRFI/bFjqHnOWBWd1NauKNfo=", "x-received": "by 2002:a63:1b53:0:b0:3fd:168e:d9a with SMTP id b19-20020a631b53000000b003fd168e0d9amr4681929pgm.617.1655388081210; Thu, 16 Jun 2022 07:01:21 -0700 (PDT)", "from": "Luis <luis#gmail.com>", "date": "Thu, 16 Jun 2022 09:01:08 -0500", "message-id": "<CAL0BCDnijtvACn6Y408hX6+XDRih6zKg+td6digWxcT7khWrBA#mail.gmail.com>", "subject": "Facturacion electronica", "to": "luis#ton.edu.co", "content-type": "multipart/mixed; boundary=\"0000000000008bea1805e191122e\"", "return-path": "luis#gmail.com", "x-ms-exchange-organization-expirationstarttime": "16 Jun 2022 14:01:22.8465 (UTC)", "x-ms-exchange-organization-expirationstarttimereason": "OriginalSubmit", "x-ms-exchange-organization-expirationinterval": "1:00:00:00.0000000", "x-ms-exchange-organization-expirationintervalreason": "OriginalSubmit", "x-ms-exchange-organization-network-message-id": "08cd21ef-317f-4b77-cff7-08da4fa0b224", "x-eopattributedmessage": "0", "x-eoptenantattributedmessage": "3855fd0e-2e9a-4fcc-9552-878a0fe4a05d:0", "x-ms-exchange-organization-messagedirectionality": "Incoming", "x-ms-publictraffictype": "Email", "x-ms-exchange-organization-authsource": "SN1NAM02FT0046.eop-nam02.prod.protection.outlook.com", "x-ms-exchange-organization-authas": "Anonymous", "x-ms-office365-filtering-correlation-id": "08cd21ef-317f-4b77-cff7-08da4fa0b224", "x-ms-traffictypediagnostic": "DM5PR1301MB2218:EE_", "x-ms-exchange-organization-scl": "1", "x-microsoft-antispam": "BCL:0;", "x-forefront-antispam-report": "CIP:209.85.215.182;CTRY:US;LANG:es;SCL:1;SRV:;IPV:NLI;SFV:NSPM;H:mail-pg1-f182.google.com;PTR:mail-pg1-f182.google.com;CAT:NONE;SFS:(13230016)(84050400002)(42186006)(1096003)(4006050)(6916009)(5660300002)(76482006)(356005)(7636003)(21480400003)(8676002)(86362001)(7596003)(7116003)(21470400002)(75640400001)(73392003)(55446002)(33964004)(26005)(336012)(82202003)(3480700007)(6666004)(564344004)(563144003);DIR:INB;", "x-ms-exchange-crosstenant-originalarrivaltime": "16 Jun 2022 14:01:22.7840 (UTC)", "x-ms-exchange-crosstenant-network-message-id": "08cd21ef-317f-4b77-cff7-08da4fa0b224", "x-ms-exchange-crosstenant-id": "3855fd0e-2e9a-4fcc-9552-878a0fe4a05d", "x-ms-exchange-crosstenant-authsource": "SN1NAM02FT0046.eop-nam02.prod.protection.outlook.com", "x-ms-exchange-crosstenant-authas": "Anonymous", "x-ms-exchange-crosstenant-fromentityheader": "Internet", "x-ms-exchange-transport-crosstenantheadersstamped": "DM5PR1301MB2218", "x-ms-exchange-transport-endtoendlatency": "00:00:03.4778129", "x-ms-exchange-processed-by-bccfoldering": "15.20.5353.014", "x-microsoft-antispam-mailbox-delivery": "ucf:0;jmr:0;auth:0;dest:I;ENG:(910001)(944506458)(944626604)(920097)(930097);", "x-microsoft-antispam-message-info": "rheidSJ3gyr1XepOaJ17S9LjRMc9FjOc8VPhMFGDvlLrCoHayxpaJN2Xe+/79unbyGbEPqNlKy+ouyW/kWiWbMjtkimlHzHZDBB3456/JLb3xkUdbuBmNwBvLvuPQ+9nqW1c1q9zHryvsGAAWnzn0CS8CZAziQjbABYTxkKLPDe0K0vTh+Un0e3x+kQgveI8CQE9UPgejQn8lAtcPD0DcAt6OB92NrlcEGlG7oEuPkTrZg1P5zVFaN/mC1F1FC0uujUcq/qCjV6wRWiN+5xRDpwMuJBdWCxL33+K05dXAt34tEDcwEy/y2DGgwsGPU6vVSnLee6M3zoJ9S4Uj02MsengV4UD80Yex2ETnr/jaq9axK/zAWCX4TTa9joBF998NhCewoerqVS7Quq+4PkYkNmaB1Cqw8SCOCNE+sktY+0E8caKjGs9/3+AttiVzj6XK1kr7cz/2M/ub9e4zALY+OxDTY4L5oxv73wH0TY9EjTc7nEFyjLe8GYM3RQ0zcIaSGKDKHv2QBqYcQgH866End0ScFqTKSAqMGez2SxF4AblBQjpLxbuIrWre1k/+JkiCrqWhlNcdOyxgrLksANeyTsT41L8uRXNqCzqc99JPqYm+j+4b1FHDhC9QDhY9aCx+A/OkvxY2+6EpvYF911eroNYTV/JEWL0bRhDIn86VY65QdfjgBRKASVTHbyMFVMjKppXK3NaP4bt2WZZuk4ucxTjdlcS5e0+MFz1zviXwXp86JCCJOcBGdbPjo2rSzvJsKhckhXzPX+A7K39FBLTDYbQYxnPp15gRTLGH/J9ani1CUCxP3AWwHnwnQp5zzD0Gqn2Gf164Pnsrnc7rCYr/6Ohj8nr8RAMpTcmj0MRJLM5cj0G12Y5sYmeg49KY5bqH4Ouo8+IqXtYNzweNRe1uA0BGbf7EzbfHxjavfrzY7tdJn4cXdfjtAxKq+SNdHBOz7yufUjGeNNglrNqk4ednOsBUD3C2Tr/NlUG1H59j/sXUc6RD9eS6D+Jf+4vz5b6cHxefgW6fCa6H9P2UxdUf6++rpZgIhL9EkmZCEahnfxc9xYMpBFavIz1S5HvCfLmZhTBo1HR48NCHMoUC1hmZ7fUsPOAsR8hLyLLnhC9l5/IJmblBHn1Im7TvQyhReiyysKN4sYy29KIuhlwujihAKK6GpjyMU3A1NSATiL870pMy3RCIn3FbdphADYbjLuG1sUwi47eO3lF8w6NRo91YlTEM32F5wi9YKFTp/eh2RYnbH0KAijFImSbEHCL58EGjcK5iq08l7qLyYjgrMdgR7mL5EDaWJw3rziHgzxbU7ETA8PKUt3sOIJ1iGGFQvhzdGO+saxN7GD9WzMmf+Jjp2pQ3Jgcidg52/5gIBogmrCc6WtCrXrqBbmYipu2vhsn73cd5RWJNUltifwlnL3v3QSXRyx6xiExI5IF6j7dn1fBn2jDLcEZWc5D1WPajgGu9y2ZWYXzblwya8ZY0RW28qBWuxqjkOf34tF6hJTaXcSlbg7936dtoor2WA6Cd0CUDuShP+vny9uOcXWQk6Oh59gxc56pk3rZoWGQ4tCK5q0=", "mime-version": "1.0" } }, "uid": "2243", "attachments": [{ "path": "C:\\Users\\usuario\\Desktop\\ioio\\Proyectos\\ioio\\2022-06-16\\1655388696749.oioio.zip" }] }]
The attachments part, is at the end of the JSON, and this is what I´m trying from JS
const jsonData = require('./prueba.json');
var strngJson = JSON.parse(JSON.stringify(jsonData))
console.log(strngJson)
console.log(jsonData.attachments.path);
//console.log(data.attachments.path[0]);
As i said, i´m really new with JS; son any explanation on how it will work, will be really appreciate it! Thanks a lot
I think your problem is that you are getting an array from that json and then you have the same problem again, I mean the attachments is another array.
So you will have to do the following:
const jsonData = require("./prueba.json");
var strngJson = JSON.parse(JSON.stringify(jsonData));
console.log(strngJson);
console.log(strngJson[0].attachments[0].path);

Zapier Results from `triggers.new_booking.operation.perform` must be an array of objects

I am building a zapier integration for an app. The app returns a JSON response like this...
{
result: "Success",
message: "Showing a total of 1 bookings",
bookings: {
42: {
event: {
event_name: "Chris's Event",
event_date_uk: "Saturday 22nd Jun 2019"
}
}
}
}
In my zapier parser, I have the following....
const options = {
url: bundle.authData.url+`/api/v1/bookings`,
method: 'GET',
headers: {
'Accept': 'application/json'
},
params: {
'key': bundle.authData.api_key,
'secret': bundle.authData.client_secret,
'booking_id': 42,
'scope': 'full'
},
}
return z.request(options)
.then((response) => {
response.throwForStatus();
const results = z.JSON.parse(response.content);
return results["bookings"];
});
However, when I test, I get the following....
Results from triggers.new_booking.operation.perform must be an array of objects. We got {"42": {"event": {"event_name": "Chris's Event", "event_date_uk": "Saturday 22nd Jun 2019"}}}.
I thought JSON.parse did return an object? And from what I can see I have returned an array of objects. Any ideas what Im doing wrong?
This contains an array of objects (bookings):
{
"result": "Success",
"message": "Showing a total of 1 bookings",
"bookings": [
{
"42": {
"event": {
"event_name": "Chris's Event",
"event_date_uk": "Saturday 22nd Jun 2019"
}
}
}
]
}
Edit: To access the event property in your JSON it's bookings.42.event where in JSON above it's bookings[0].42.event.

Why getting unexpected token with Twilio?

Given the sample code from Twilio:
const accountSid = 'ACf37a37065e79fb1a7a594f294cb3b190';
const authToken = 'your_auth_token';
const client = require('twilio')(accountSid, authToken);
client.messages
.create({
body: 'This is the ship that made the Kessel Run in fourteen parsecs?',
from: '+15017122661',
to: '+15558675310'
})
.then(message => console.log(message.sid));
How do you get the error code and error message?
Here's the output (as per the quickguide)
{
"account_sid": "ACf37a37065e79fb1a7a594f294cb3b190",
"api_version": "2010-04-01",
"body": "This is the ship that made the Kessel Run in fourteen parsecs?",
"date_created": "Thu, 30 Jul 2015 20:12:31 +0000",
"date_sent": "Thu, 30 Jul 2015 20:12:33 +0000",
"date_updated": "Thu, 30 Jul 2015 20:12:33 +0000",
"direction": "outbound-api",
"error_code": null,
"error_message": null,
"from": "+15017122661",
"messaging_service_sid": "MGXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
"num_media": "0",
"num_segments": "1",
"price": -0.00750,
"price_unit": "USD",
"sid": "MMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
"status": "sent",
"subresource_uris": {
"media": "/2010-04-01/Accounts/ACf37a37065e79fb1a7a594f294cb3b190/Messages/SMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Media.json"
},
"to": "+15558675310",
"uri": "/2010-04-01/Accounts/ACf37a37065e79fb1a7a594f294cb3b190/Messages/SMXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.json"
}
I'm trying this:
client.messages
.create({
body: 'This is the ship that made the Kessel Run in fourteen parsecs?',
from: '+15017122661',
to: '+15558675310'
})
.then(message => console.log(message.sid));
.then(message => console.log(message.error_code));
But doesn't work. I get unexpected token.
Ideally I want to log the error code and message and other information like date_sent, etc.. so I validate and send the right info back to the client.
Any help will be greatly appreciated.
thanks
You're getting the token thing because you have a semicolon between the two then() (observe the end of the first line and the beginning of the second line in code below)
.then(message => console.log(message.sid)); // <----
.then(message => console.log(message.error_code));
So, try something like this:
client.messages
.create({
body: 'This is the ship that made the Kessel Run in fourteen parsecs?',
from: '+15017122661',
to: '+15558675310'
})
.then(message => {
console.log(message.sid);
console.log(message.error_code || 'no error');
});

Merge objects based on date in javascript array

I have an object
{
YHOO: [
{
date: Fri Apr 12 1996 00:00:00 GMT-0400 (EDT),
open: 25.25,
high: 43,
low: 24.5,
close: 33,
volume: 408720000,
adjClose: 1.38,
symbol: 'YHOO'
},
...
{
date: Thu Nov 14 2013 00:00:00 GMT-0500 (EST),
open: 35.07,
high: 35.89,
low: 34.76,
close: 35.69,
volume: 21368600,
adjClose: 35.69,
symbol: 'YHOO'
}
],
GOOGL: [
{
date: Thu Aug 19 2004 00:00:00 GMT-0400 (EDT),
open: 100,
high: 104.06,
low: 95.96,
close: 100.34,
volume: 22351900,
adjClose: 100.34,
symbol: 'GOOGL'
},
...
{
date: Thu Nov 14 2013 00:00:00 GMT-0500 (EST),
open: 1033.92,
high: 1039.75,
low: 1030.35,
close: 1035.23,
volume: 1166700,
adjClose: 1035.23,
symbol: 'GOOGL'
}
],
...
}
How do I alter this object so it becomes an array with
[
{
date: Fri Apr 12 1996 00:00:00 GMT-0400 (EDT),
YHOO: 33,
GOOG: 100.34
},
...
]
I know it can become a problem that they potentially not have the same dates, so I guess I should just say that one of the companies have the right dates, and then merge the other companies to these dates and omit those dates that are not in the already selected company.
I guess I should do something like
var data = [];
obj.YHOO.forEach((quote) => {
data.push({
date: quote.date,
YHOO: quote.price,
GOOG: ?
});
});
and instead of the question mark, I can loop through all the objects in array.GOOG and check if the date matches quote.date.
The big problem is that this seems quite computational heavy and the names of the companies can vary, so I cannot guarantee that YHOO and GOOG are present.

Unable to parse a JSON in jade

I am trying to parse a JSON object that comes in from mongodb but am unable to use it for some reason after parsing.
Here is the piece of javascript function that I am using
-function check(category) {
-var temp = JSON.stringify(category);
-return JSON.parse(temp);
-}
.row.wow.fadeInRight.animated(data-wow-offset='30', data-wow-duration='1.5s', data-wow-delay='0.15s')
.col-md-12
if(articles)
#client-feedbacks.owl-carousel.owl-theme
each article in articles
-var category = article.categories
.feedback-box
.client-image.hidden-xs
img(src=article._.image.fit(250,250), alt='article image')
// MESSAGE OF THE CLIENT
h6.article-title
a(href='/blog/post/' + article.slug, itemprop='url')!= article.title
br
.message!= article.content.brief
// CLIENT INFORMATION
.client
.quote.red-text
i.icon-fontawesome-webfont-294
.client-info
a.client-namea(href='/blog/post/' + article.slug, itemprop='url')!= prettyDate(article.publishedDate)
-var categories = check(category)
.client-company(itemtype="http://schema.org/BlogPosting") #{category[0].name}
Here is what the object looks like when i use json .stringify
{ updatedBy: 5498631c5cbfa2d03f4570e6,
updatedAt: Mon Feb 09 2015 00:30:48 GMT+0530 (IST),
createdBy: 5498631c5cbfa2d03f4570e6,
createdAt: Mon Feb 09 2015 00:30:48 GMT+0530 (IST),
key: 'mongoose',
name: 'Mongoose',
_id: 54d7b2601d88fc4f69d0e081,
__v: 0 },{ updatedBy: 5498631c5cbfa2d03f4570e6,
updatedAt: Mon Feb 09 2015 00:31:44 GMT+0530 (IST),
createdBy: 5498631c5cbfa2d03f4570e6,
createdAt: Mon Feb 09 2015 00:31:44 GMT+0530 (IST),
key: 'green-berrets',
name: 'Green Berrets',
_id: 54d7b298fe85a1c4698b2ec3,
__v: 0 }
I am confused on how to parse it as most of the things i tried did not work

Categories