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
}
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).
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?
Related
I'm trying to add the collection field (name and family) to my metadata using VSC. Not sure where to begin or how to do it. Any help appreciated. Thanks!
{
"name": "Solflare X NFT",
"symbol": "",
"description": "Celebratory Solflare NFT for the Solflare X launch",
"seller_fee_basis_points": 0,
"image": "https://www.arweave.net/abcd5678?ext=png",
"animation_url": "https://www.arweave.net/efgh1234?ext=mp4",
"external_url": "https://solflare.com",
"attributes": [
{ "trait_type": "web", "value": "yes" },
{ "trait_type": "mobile", "value": "yes" },
{ "trait_type": "extension", "value": "yes" }
],
"collection": { "name": "Solflare X NFT", "family": "Solflare" },
"properties": {
"files": [
{
"uri": "https://www.arweave.net/abcd5678?ext=png",
"type": "image/png"
},
{
"uri": "https://watch.videodelivery.net/9876jkl",
"type": "unknown",
"cdn": true
},
{ "uri": "https://www.arweave.net/efgh1234?ext=mp4", "type": "video/mp4" }
],
"category": "video",
"creators": [
{ "address": "SOLFLR15asd9d21325bsadythp547912501b", "share": 100 }
]
}
}
I have a very complex JSON structure in which I have nested JSON and arrays. From that I want to fetch a object(json) with key metadata. Sequence of the JSON is not fixed for the each time. How could I fetch value for that JSON?
This is sample json structure
{
"id": "*******",
"name": "createNewApiKey",
"start_time": 1543504061.474,
"end_time": 1543504062.059,
"parent_id": "******",
"aws": {
"function_arn": "********",
"resource_names": [
"****"
],
"account_id": "******"
},
"trace_id": "1-5c0000bc-*****",
"origin": "AWS::Lambda::Function",
"subsegments": [
{
"id": "5d680f995ca8cfd9",
"name": "*******",
"start_time": 1543504061.503,
"end_time": 1543504061.977,
"fault": true,
"error": true,
"cause": {
"exceptions": [
{
"stack": [
{
"path": "/var/task/node_modules/aws-xray-sdk-core/lib/patchers/aws_p.js",
"line": 77,
"label": "captureAWSRequest [as customRequestHandler]"
},
{
"path": "/var/runtime/node_modules/aws-sdk/lib/service.js",
"line": 267,
"label": "addAllRequestListeners"
},
{
"path": "/var/runtime/node_modules/aws-sdk/lib/service.js",
"line": 191,
"label": "makeRequest"
},
{
"path": "/var/runtime/node_modules/aws-sdk/lib/service.js",
"line": 499,
"label": "svc.anonymous function [as getSecretValue]"
},
{
"path": "/var/task/index.js",
"line": 34,
"label": "exports.handler"
}
],
"message": "*****",
"type": "ResourceNotFoundException",
"remote": true
}
],
"working_directory": "/var/task"
},
"http": {
"response": {
"status": 400
}
},
"aws": {
"operation": "GetSecretValue",
"region": "eu-west-1",
"request_id": "******",
"retries": 0
},
"namespace": "aws",
"subsegments": [
{
"id": "*****",
"name": "Metadata",
"start_time": 1543504061.981,
"end_time": 1543504062.017,
"metadata": {
"default": {
"inputData": {
"clientName": "a",
"productOwner": "dev"
},
"response": "Wrong client ID"
}
}
}
]
},
{
"id": "********",
"name": "Initialization",
"start_time": 1543504060.726,
"end_time": 1543504061.47,
"aws": {
"*****"
}
},
{
"id": "********",
"name": "annotations",
"start_time": 1543504061.477,
"end_time": 1543504061.478,
"annotations": {
"User": "dev",
"Name": "a"
}
}
]
}
** may contain either JSON or array
Here I want to fetch below JSON
{
"inputData": {
"id": "*****",
"givenClientName": "abc1012",
"productOwner": "dev"
},
"response": "** successfully"
}
You need a recursive search function.
The following ES6 snippet recursively walks through all nodes in obj until it finds an occurrence of key.
It does not assume that nodes containing an array are identified with 'subsegments'. But you could do k == 'subsegments' && Array.isArray(obj[k]) to enforce this rule.
search = (obj, key) => {
let res = null;
(searchNode = obj => Object.keys(obj).some(k => {
if(k == key) {
res = obj[k];
return true;
}
return Array.isArray(obj[k]) && obj[k].some(searchNode);
}))(obj);
return res;
}
obj = {
"id": "*******",
"name": "createNewApiKey",
"start_time": 1543504061.474,
"end_time": 1543504062.059,
"parent_id": "******",
"subsegments": [
{
"subsegments": [
{
"subsegments": [
{
"subsegments": [
{
"metadata": {
"default": {
"inputData": {
"id": "*****",
"givenClientName": "abc1012",
"productOwner": "dev"
},
"response": "** successfully"
}
}
}
]
}
]
}
]
}
]
};
console.log(search(obj, 'metadata'))
If you are looking only for the first element of an array then this you can try.
var a = {
"subsegments": [{
"subsegments": [{
"subsegments": [{
"subsegments": [{
"metadata": {
"default": {
"inputData": {
"id": "",
"givenClientName": "abc1012",
"productOwner": "dev"
},
"response": " successfully"
}
}
}]
}]
}, {
"subsegments": [{
"subsegments": [{
"metadata": {
"default": {
"inputData": {
"id": "",
"givenClientName": "abc1012",
"productOwner": "dev"
},
"response": " successfully"
}
}
}]
}]
}]
}]
}
function test(params) {
if (!params) {
return null;
}
if (params.default) {
return params.default;
} else if (Array.isArray(params)) {
var subsegments = params[0].subsegments || params[0].metadata;
return test(subsegments);
} else {
return test(params.subsegments);
}
}
console.log(test(a));
Here is one possibility, searching depth-first for an item with a given key, returning null if it's not found:
const findFirstKey = (name) => (obj) => !(obj instanceof Object)
? null
: name in obj
? obj[name]
: Object.keys(obj).reduce((res, key) => res || findFirstKey(name)(obj[key]), null)
const response = {"aws": {"account_id": "******", "function_arn": "********", "resource_names": ["****"]}, "end_time": 1543504062.059, "id": "*******", "name": "createNewApiKey", "origin": "AWS::Lambda::Function", "parent_id": "******", "start_time": 1543504061.474, "subsegments": [{"aws": {"operation": "GetSecretValue", "region": "eu-west-1", "request_id": "******", "retries": 0}, "cause": {"exceptions": [{"message": "*****", "remote": true, "stack": [{"label": "captureAWSRequest [as customRequestHandler]", "line": 77, "path": "/var/task/node_modules/aws-xray-sdk-core/lib/patchers/aws_p.js"}, {"label": "addAllRequestListeners", "line": 267, "path": "/var/runtime/node_modules/aws-sdk/lib/service.js"}, {"label": "makeRequest", "line": 191, "path": "/var/runtime/node_modules/aws-sdk/lib/service.js"}, {"label": "svc.anonymous function [as getSecretValue]", "line": 499, "path": "/var/runtime/node_modules/aws-sdk/lib/service.js"}, {"label": "exports.handler", "line": 34, "path": "/var/task/index.js"}], "type": "ResourceNotFoundException"}], "working_directory": "/var/task"}, "end_time": 1543504061.977, "error": true, "fault": true, "http": {"response": {"status": 400}}, "id": "5d680f995ca8cfd9", "name": "*******", "namespace": "aws", "start_time": 1543504061.503, "subsegments": [{"end_time": 1543504062.017, "id": "*****", "metadata": {"default": {"inputData": {"clientName": "a", "productOwner": "dev"}, "response": "Wrong client ID"}}, "name": "Metadata", "start_time": 1543504061.981}]}, {"aws": {"*****": "blah"}, "end_time": 1543504061.47, "id": "********", "name": "Initialization", "start_time": 1543504060.726}, {"annotations": {"Name": "a", "User": "dev"}, "end_time": 1543504061.478, "id": "********", "name": "annotations", "start_time": 1543504061.477}], "trace_id": "1-5c0000bc-*****"}
const meta = findFirstKey('metadata')(response)
console.log(meta)
Here you could also write const getMeta = findFirstKey('metadata') and then simply apply that function to your data.
But please note that if your data is too inconsistent, any attempt to normalize it like this can end up being problematic. If you can tame it up front, the rest of your code will likely be simpler.
I have an issue with the Postman/Node.js as in when I try to do POST method with a document attached. I want to change the name of the file before the request because two files of the same name cannot be uploaded. I want to be able to set it up so a collection can be run by anytime by my colleges. I did a workaround for Postman from http://blog.getpostman.com/2017/09/21/run-collections-with-file-uploads-using-newman/ for the file upload automatization.
My question is:
How can I take the file, change its name to something random, like test{{$timestamp}}.docx and point to the new name in that .json file again so it can be uploaded?
This is my .json file
{
"name": "Save case's documents CID CDN",
"event": [
{
"listen": "test",
"script": {
"id": "04bf1f30-c2bc-4250-97c9-9efb7afa25e3",
"type": "text/javascript",
"exec": [
"// Check the status of a request",
"pm.test(\"Addition of a document successful!\", function () {",
" pm.response.to.have.status(200);",
"});",
"// Check the response time ",
"pm.test(\"Response time is acceptable\", function () {",
" pm.expect(pm.response.responseTime).to.be.below(2000);",
"});",
"// Set documentName variable",
"var jsonData = JSON.parse(responseBody);",
"postman.setEnvironmentVariable(\"documentName\", jsonData.content.documentName);"
]
}
},
{
"listen": "prerequest",
"script": {
"id": "09a922cd-6c2a-47cb-b597-d5dcab0d45bd",
"type": "text/javascript",
"exec": [
"",
""
]
}
}
],
"request": {
"auth": {
"type": "bearer",
"bearer": [
{
"key": "token",
"value": "",
"type": "string"
}
]
},
"method": "POST",
"header": [
{
"key": "Authorization",
"value": "{{token}}"
},
{
"key": "Content-Type",
"value": "application/x-www-form-urlencoded"
}
],
"body": {
"mode": "formdata",
"formdata": [
{
"key": "document",
"value":
"C:\\Users\\User123456\\Desktop\\test.docx",
"description": "",
"type": "file",
"src": "C:\\Users\\User123456\\Desktop\\test.docx"
},
{
"key": "documentCategory",
"value": "Other",
"description": "",
"type": "text"
},
{
"key": "refCreatedBy",
"value": "{{bu_id}}",
"description": "",
"type": "text"
},
{
"key": "createdAt",
"value": "{{date}}",
"description": "",
"type": "text"
},
{
"key": "accuracy.status",
"value": "string",
"description": "",
"type": "text"
},
{
"key": "accuracy.lastModifiedDate",
"value": "{{$timestamp}}",
"description": "",
"type": "text"
},
{
"key": "accuracy.lastModifiedBy",
"value": "{{bu_id}}",
"description": "",
"type": "text"
},
{
"key": "quality.status",
"value": "sting",
"description": "",
"type": "text"
},
{
"key": "quality.lastModifiedDate",
"value": "{{$timestamp}}",
"description": "",
"type": "text"
},
{
"key": "quality.lastModifiedBy",
"value": "{{$timestamp}}",
"description": "",
"type": "text"
}
]
},
"url": {
"raw": "{{site}}/cases/{{case_id}}/documents/{{documentName}}",
"host": [
"{{site}}"
],
"path": [
"cases",
"{{case_id}}",
"documents",
"{{documentName}}"
]
},
"description": ""
},
"response": []
}
]
}
I am getting an array of specs from flipkart's API.
I am able to get this response from that API:
{
"nextUrl": "https://affiliate-api.flipkart.net/1.0/affiliate/feeds/fnkygygma/category/reh/55ab6c2673a4773ffb8e4019.json?expiresAt=1452881213871&sig=1c4c5111b6b014a71a17b229e6df6afc",
"validTill": 1452881213871,
"productInfoList": [
{
"productBaseInfoV1": {
"productId": "TDHDMH5GRSPZ3DNM",
"title": "Newhide Designer",
"productDescription": "",
"imageUrls": {
"400x400": "http://img.fkcdn.com/image/travel-document-holder/d/n/m/cdbp040739-newhide-passport-holder-designer-400x400-imadmh8zgxbrsgq6.jpeg",
"200x200": "http://img.fkcdn.com/image/travel-document-holder/d/n/m/cdbp040739-newhide-passport-holder-designer-200x200-imadmh8zgxbrsgq6.jpeg",
"unknown": "http://img.fkcdn.com/image/travel-document-holder/d/n/m/cdbp040739-newhide-passport-holder-designer-original-imadmh8zgxbrsgq6.jpeg",
"800x800": "http://img.fkcdn.com/image/travel-document-holder/d/n/m/cdbp040739-newhide-passport-holder-designer-800x800-imadmh8zgxbrsgq6.jpeg"
},
"productFamily": null,
"maximumRetailPrice": {
"amount": 1145,
"currency": "INR"
},
"flipkartSellingPrice": {
"amount": 1145,
"currency": "INR"
},
"flipkartSpecialPrice": {
"amount": 1145,
"currency": "INR"
},
"productUrl": "http://dl.flipkart.com/dl/newhide-designer/p/itmdp2nunbzffwzr?pid=TDHDMH5GRSPZ3DNM&affid=keshav",
"productBrand": "Newhide",
"inStock": true,
"codAvailable": true,
"discountPercentage": 0,
"offers": [],
"categoryPath": "[[{\"node_id\":20001,\"node_name\":\"FLIPKART_TREE\"},{\"node_id\":21183,\"node_name\":\"Lifestyle\"},{\"node_id\":21499,\"node_name\":\"Leather \\u0026 Travel Accessories\"},{\"node_id\":21960,\"node_name\":\"Wallets \\u0026 Clutches\"},{\"node_id\":21274,\"node_name\":\"Wallets \\u0026 Card Wallets\"}]]",
"styleCode": null,
"attributes": {
"size": "",
"color": "Black",
"storage": "",
"sizeUnit": "",
"displaySize": ""
}
},
"productShippingInfoV1": {
"shippingCharges": {
"amount": 0,
"currency": "INR"
},
"sellerName": null,
"sellerAverageRating": null,
"sellerNoOfRatings": 0,
"sellerNoOfReviews": 0
},
"categorySpecificInfoV1": {
"keySpecs": [
"Passport Holder",
"Passport Wallet"
],
"detailedSpecs": [],
"specificationList": [
{
"key": "General",
"values": [
{
"key": "Type",
"value": [
"Passport Organizer"
]
},
{
"key": "Ideal For",
"value": [
"Men's, Women's"
]
},
{
"key": "Material",
"value": [
"Leather, Cloth"
]
},
{
"key": "Slot for Cards",
"value": [
"Yes"
]
},
{
"key": "Slot for Passport",
"value": [
"Yes"
]
},
{
"key": "Slot for Cheque Book",
"value": [
"Yes"
]
},
{
"key": "Style Code",
"value": [
"CDBP040739"
]
},
{
"key": "Color Code",
"value": [
"Black"
]
}
]
},
{
"key": "Warranty",
"values": [
{
"key": " ",
"value": [
"1 Year Newhide warranty"
]
}
]
}
],
"booksInfo": {
"language": null,
"binding": null,
"pages": null,
"publisher": null,
"year": 0,
"authors": []
},
"lifeStyleInfo": {
"sleeve": null,
"neck": null,
"idealFor": [
"Men's",
"Women's"
]
}
}
}
}
I and not able decode
"categorySpecificInfoV1": {
"keySpecs": [
"Passport Holder",
"Passport Wallet"
],
I have tried json_decode. This gives error
Warning: json_decode() expects parameter 1 to be string, array given.
$keySpecs=$product['categorySpecificInfoV1']['keySpecs'];
$ar = json_decode($keySpecs,true);
I am new to PHP, how can I print the keyspecs from keyspecs array?
The warning is pretty clear. You need to pass the entire string you obtained from Flipkart into the json_decode() function.
See Documentation
$ar = json_decode($flipkart_result, true);
print_r($ar); //to check the array.
print_r($ar['categorySpecificInfoV1']['keySpecs']);
This should do. Post more information if this does not help.
This is the json object I get after running a script.
{
"log": {
"entries": [{
"startedDateTime": "2015-08-16T10:27:35.264Z",
"time": 35,
"request": {
"method": "GET",
"url": "http://www.google.com/",
"httpVersion": "HTTP/1.1",
"cookies": [],
"headers": [{
"name": "User-Agent",
"value": "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/534.34 (KHTML, like Gecko) PhantomJS/1.9.8 Safari/534.34"
}, {
"name": "Accept",
"value": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"
}],
"queryString": [],
"headersSize": -1,
"bodySize": -1
},
"response": {
"status": 302,
"statusText": "Found",
"httpVersion": "HTTP/1.1",
"cookies": [],
"headers": [{
"name": "Cache-Control",
"value": "private"
}, {
"name": "Content-Type",
"value": "text/html; charset=UTF-8"
}, {
"name": "Location",
"value": "http://www.google.co.in/?gfe_rd=cr&ei=mWXQVZiNLaHv8wehp6jYDw"
}, {
"name": "Content-Length",
"value": "261"
}, {
"name": "Date",
"value": "Sun, 16 Aug 2015 10:27:37 GMT"
}, {
"name": "Server",
"value": "GFE/2.0"
}, {
"name": "Connection",
"value": "keep-alive"
}],
"redirectURL": "",
"headersSize": -1,
"bodySize": 261,
"content": {
"size": 261,
"mimeType": "text/html; charset=UTF-8"
}
},
"cache": {},
"timings": {
"blocked": 0,
"dns": -1,
"connect": -1,
"send": 0,
"wait": 35,
"receive": 0,
"ssl": -1
},
"pageref": "http://www.google.com"
}, .....
]
}
}
In my javascript, I am trying to access every object. But its not working.
Lets say for example, I assign this json object to data:
data = JSON.parse({... that whole json object...});
console.log(data["log"]["entries"][0]);
I get nothing. I am using this inside node. What mistake am I doing here ?
You should treat this as object, here is a working fiddle :
https://jsfiddle.net/8jqvvmc6/3/
var jsonData = {
"log": {
"entries": [{
"startedDateTime": "2015-08-16T10:27:35.264Z",
"time": 35,
"request": {
"method": "GET",
"url": "http://www.google.com/",
"httpVersion": "HTTP/1.1",
"cookies": [],
"headers": [{
"name": "User-Agent",
"value": "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/534.34 (KHTML, like Gecko) PhantomJS/1.9.8 Safari/534.34"
}, {
"name": "Accept",
"value": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"
}],
"queryString": [],
"headersSize": -1,
"bodySize": -1
},
"response": {
"status": 302,
"statusText": "Found",
"httpVersion": "HTTP/1.1",
"cookies": [],
"headers": [{
"name": "Cache-Control",
"value": "private"
}, {
"name": "Content-Type",
"value": "text/html; charset=UTF-8"
}, {
"name": "Location",
"value": "http://www.google.co.in/?gfe_rd=cr&ei=mWXQVZiNLaHv8wehp6jYDw"
}, {
"name": "Content-Length",
"value": "261"
}, {
"name": "Date",
"value": "Sun, 16 Aug 2015 10:27:37 GMT"
}, {
"name": "Server",
"value": "GFE/2.0"
}, {
"name": "Connection",
"value": "keep-alive"
}],
"redirectURL": "",
"headersSize": -1,
"bodySize": 261,
"content": {
"size": 261,
"mimeType": "text/html; charset=UTF-8"
}
},
"cache": {},
"timings": {
"blocked": 0,
"dns": -1,
"connect": -1,
"send": 0,
"wait": 35,
"receive": 0,
"ssl": -1
},
"pageref": "http://www.google.com"
}]
}
};
alert(jsonData["log"]["entries"][0]);
See the fiddle to see how it should work in your case. Also I assume data should be a local variable, it might get overwritten somewhere before your code executes. Don't pollute the global scope I guess.
That does not work!
data = JSON.parse({... that whole json object...});
because
data = {... that whole json object...};
is already an object.
But if you have
data = JSON.parse('{... that whole json object...}');
then it should be parsed first, to convert a string to an JSON compliant object.