I am using below code for resizing multiple images:
Sample request1 :/images/0/products/1/10x10$20x20$30x30/test.jpg
Sample request 2:/images/0/banners/10x10$20x20$30x30/test.jpg
Here, I am trying to process image resize for two types of images. One of product and one of banners.Sample json I am using for request:
{
"Records": [
{
"cf": {
"config": {
"distributionDomainName": "d30ctzvvm0c9tj.cloudfront.net",
"distributionId": "E7L07HTI8617C",
"eventType": "origin-response"
},
"request": {
"clientIp": "103.217.247.2",
"headers": {
"user-agent": [
{
"key": "User-Agent",
"value": "Amazon CloudFront"
}
],
"via": [
{
"key": "Via",
"value": "1.1 126c88e8d3434fec67dab0faaa786e61.cloudfront.net (CloudFront)"
}
],
"upgrade-insecure-requests": [
{
"key": "Upgrade-Insecure-Requests",
"value": "1"
}
],
"accept-encoding": [
{
"key": "Accept-Encoding",
"value": "gzip"
}
],
"x-forwarded-for": [
{
"key": "X-Forwarded-For",
"value": "103.217.247.2"
}
],
"host": [
{
"key": "Host",
"value": "test-cloudfront-shirsh.s3.amazonaws.com"
}
]
},
"method": "GET",
"origin": {
"s3": {
"authMethod": "origin-access-identity",
"customHeaders": {},
"domainName": "test-cloudfront-shirsh.s3.amazonaws.com",
"path": "",
"region": "ap-south-1"
}
},
"querystring": "d=10x10$20x20$30x30",
"uri": "/images/0/banners/10x10$20x20$30x30/test.jpg"
},
"response": {
"headers": {
"x-amz-request-id": [
{
"key": "x-amz-request-id",
"value": "1B822F690E9022FF"
}
],
"x-amz-id-2": [
{
"key": "x-amz-id-2",
"value": "rfK2MUwZnmBmp5KssOJfKK+hTLNwHiNrxFAwqbWRE2yXt8PQzEWNgJmhVSh488Me7wXupuu8w8A="
}
],
"date": [
{
"key": "Date",
"value": "Fri, 12 Oct 2018 10:04:55 GMT"
}
],
"server": [
{
"key": "Server",
"value": "AmazonS3"
}
],
"content-type": [
{
"key": "Content-Type",
"value": "application/xml"
}
],
"transfer-encoding": [
{
"key": "Transfer-Encoding",
"value": "chunked"
}
]
},
"status": "404",
"statusDescription": "Forbidden"
}
}
}
]
}
For above request(Banner):
Source Image Bucket: /images/0/banners/test.jpg
Sizes to be geneated: 10x10, 20x20 ,30x30
Dest Image Bucket:
/images/0/banners/10x10/test.jpg
/images/0/banners/20x20/test.jpg
/images/0/banners/30x30/test.jpg
However, it is saving only for last image : /images/0/banners/30x30/test.jpg
My Js code:
'use strict';
const http = require('http');
const https = require('https');
const querystring = require('querystring');
const AWS = require('aws-sdk');
const S3 = new AWS.S3({
signatureVersion: 'v4',
});
const Sharp = require('sharp');
// set the S3 and API GW endpoints
const BUCKET = 'test-cloudfront-shirsh';
exports.handler = (event, context, callback) => {
let response = event.Records[0].cf.response;
console.log("Response Header::" + JSON.stringify(response));
console.log("Response status code :%s", response.status);
const variables = {
allowedDimension : [],
};
// check if image is not present
if (response.status == 404 || response.status == 403) {
let request = event.Records[0].cf.request;
let params = querystring.parse(request.querystring);
console.log("d=" + params.d);
// if there is no dimension attribute, just pass the response
if (!params.d) {
callback(null, response);
return;
}
variables.allowedDimension=params.d.split("$");
if(variables.allowedDimension.length >=1 ){
var prod_regex=/\/images\/0\/products\/(\d+)/;
var banner_regex=/\/images\/0\/banners/;
let path,prefix, originalKey, match, width, height, requiredFormat, imageName,bucketKey,key,dimArray,dimensionRatios;
console.log("Using forEach");
variables.allowedDimension.forEach(function(dimension, index){
path = request.uri;
dimensionRatios= path.split('/');
console.log("Path::" + path);
try {
// "/images/0/banners/20x20/jpg/abc.jpg";
if(banner_regex.test(path)){
console.log("Regex for banner");
key = path.replace(dimensionRatios[4],dimension);
dimArray = dimension.split("x");
match = key.match(/\/(.*)\/(.*)\/(.*)\/(\d+)x(\d+)\/(.*)/);
prefix = match[1]+"/"+match[2]+"/"+match[3]+ "/";
imageName = match[6];
}if(prod_regex.test(path)){
console.log("Regex for product");
key = path.replace(dimensionRatios[5],dimension);
dimArray = dimension.split("x");
match=key.match(/\/(.*)\/(.*)\/(.*)\/(\d+)\/(\d+)x(\d+)\/(.*)/);
prefix = match[1]+"/"+match[2]+"/"+match[3]+ "/" + match[4] + "/";
imageName = match[7];
}
width = parseInt(dimArray[0],10);
height = parseInt(dimArray[1],10);
requiredFormat = "jpg";
originalKey = prefix + imageName;
bucketKey= prefix + dimension + "/" + imageName;
console.log("dimension::" + dimension + "\nkey::"+ key +"\npath::"+path +"\nPrefx:::" + prefix + "\nimageName:" +imageName
+ "\nWidthxHeight" + width + "x" + height + "\nBucket Key:" + bucketKey+"\nOrig Key::" + originalKey);
}
catch (err) {
console.log("no prefix present.."+err);
}
// get the source image file
S3.getObject({ Bucket: BUCKET, Key: originalKey }).promise()
// perform the resize operation
.then(data => Sharp(data.Body)
.resize(width, height)
.ignoreAspectRatio()
.toFormat(requiredFormat)
.toBuffer()
)
.then(buffer => {
console.log("Putting image for buckt key :" + bucketKey );
// save the resized object to S3 bucket with appropriate object
// key.
S3.putObject({
Body: buffer,
Bucket: BUCKET,
ContentType: 'image/' + requiredFormat,
CacheControl: 'max-age=31536000',
Key: bucketKey,
StorageClass: 'STANDARD'
}).promise()
// even if there is exception in saving the object we send back
// the generated
// image back to viewer below
.catch(error => { console.log("Exception while writing resized image to bucket",error)});
response.status = 200;
response.body = buffer.toString('base64');
response.bodyEncoding = 'base64';
response.headers['content-type'] = [{ key: 'Content-Type', value: 'image/' + requiredFormat }];
callback(null, response);
})
.catch( err => {
console.log("Exception while reading source image with error :",err);
});
// generate a binary response with resized image
});
// read the S3 key from the path variable.
// Ex: path variable /images/100x100/webp/image.jpg
}else{
callback(null, response);
}
// read the required path. Ex: uri /images/100x100/webp/image.jpg
} // end of if block checking response statusCode
else {
// allow the response to pass through
callback(null, response);
}
};
Related
Assume that this is the changelog of a Jira issue
{
"expand": "renderedFields,names,schema,operations,editmeta,changelog,versionedRepresentations",
"id": "72194",
"self": "https://jira.instance.net/rest/api/2/issue/72194",
"key": "TII-627",
"changelog": {
"startAt": 0,
"maxResults": 1,
"total": 1,
"histories": [
{
"id": "12345",
"author": {
"self": "https://jira.instance.net/rest/api/2/user?accountId=xxxxxxxxxxx",
"accountId": "xxxxxxxxxxxx",
"emailAddress": "xxx#yy.com",
"avatarUrls": {},
"displayName": "John Doe",
"active": true,
"timeZone": "Anywhere",
"accountType": "atlassian"
},
"created": "2023-02-07T10:30:02.897+0530",
"items": [
{
"field": "status",
"fieldtype": "jira",
"fieldId": "status",
"from": "10000",
"fromString": "To Do",
"to": "5",
"toString": "Resolved"
}
]
}
]
},
"fields": {
"status": {
"self": "https://jira.instance.net/rest/api/2/status/5",
"description": "A resolution has been taken, and it is awaiting verification by reporter. From here issues are either reopened, or are closed.",
"iconUrl": "something",
"name": "Resolved",
"id": "5",
"statusCategory": {
"self": "https://jira.instance.net/rest/api/2/statuscategory/3",
"id": 3,
"key": "done",
"colorName": "green",
"name": "Done"
}
}
}
}
In this changelog you can see that the issue with "key": "TII-627" was first transition to done statuscategory aka Resolved status on "created": "2023-02-07T10:30:02.897+0530"
I want to get this first transition to done and print it in a table for all issues in the project like this
issue_key, first_resolved_at
for the eg. above it would look like this
TII-627, 2023-02-07T10:30:02.897+0530
I have tried using the following ruby script but I am getting the first resolved date empty please let me know what can I do
require 'jira-ruby'
# JIRA API credentials
jira_username = '<your-jira-username>'
jira_token = '<your-jira-api-token>'
jira_domain = '<your-jira-instance-domain>'
# initialize client
options = {
:username => jira_username,
:password => jira_token,
:site => "https://#{jira_domain}",
:context_path => '',
:auth_type => :basic
}
client = JIRA::Client.new(options)
# Define the issue key as a command line argument
issue_key = ARGV[0]
# Log the start time of the script
start_time = Time.now
puts "Start time: #{start_time}"
# Get the issue information
begin
issue = client.Issue.find(issue_key)
issue_status_category = issue.fields['status']['statusCategory']['name']
# If issue has already reached done status, retrieve the transitions
if issue_status_category == 'Done'
transitions = issue.transitions
first_resolved_at = nil
last_resolved_at = nil
# Retrieve the first and last resolved dates
transitions.each do |transition|
transition_status_category = transition['to']['statusCategory']['name']
if transition_status_category == 'Done'
transition_created_at = DateTime.parse(transition['created'])
if first_resolved_at.nil?
first_resolved_at = transition_created_at
end
last_resolved_at = transition_created_at
end
end
# Print the results
puts "Issue Key: #{issue.key}"
puts "First Resolved At: #{first_resolved_at}"
puts "Last Resolved At: #{last_resolved_at}"
else
puts "Issue has not yet reached Done status."
end
rescue Exception => e
# Log the error
puts "Error: #{e}"
end
# Log the end time of the script
end_time = Time.now
puts "End time: #{end_time}"
I am closing the question. I was able to figure out another way using JS
const axios = require("axios");
async function getFirstResolvedDate(jiraUsername, jiraToken, jiraDomain, issues) {
for (const issue of issues) {
let changelogs = [];
let url = jiraDomain + "/rest/api/2/issue/" + issue + "?expand=changelog";
let response = await axios({
method: "get",
url: url,
headers: {
"Authorization": "Basic " + Buffer.from(jiraUsername + ":" + jiraToken).toString("base64"),
"Content-Type": "application/json",
}
});
let data = response.data;
let changelog = data.changelog.histories;
if (!Array.isArray(changelog)) {
changelog = [changelog];
}
for (const history of changelog) {
let items = history.items;
for (const item of items) {
if (item.field === "status" && (item.toString === "Resolved" || item.toString === "Invalid")) {
let firstResolvedAt = history.created;
changelogs.push({
issue_key: issue,
first_resolved_at: firstResolvedAt
});
break;
}
}
}
let earliestDate = new Date(Math.min.apply(null, changelogs.map(function(c) {
return new Date(c.first_resolved_at);
})));
let formattedDate = earliestDate.toISOString();
url = jiraDomain + "/rest/api/2/issue/" + issue;
let body = {
fields: {
customfield_xxx: formattedDate
}
};
response = await axios({
method: "put",
url: url,
headers: {
"Authorization": "Basic " + Buffer.from(jiraUsername + ":" + jiraToken).toString("base64"),
"Content-Type": "application/json",
},
data: body
});
if (response.status === 200 || response.status === 204) {
console.log("Successfully updated first resolved date for issue " + issue);
} else {
console.error(response);
}
}
}
const jiraUsername = 'xxx';
const jiraToken = "xxx";
const jiraDomain = "https://xxx";
const issues = ['xxx-1'];
getFirstResolvedDate(jiraUsername, jiraToken, jiraDomain, issues)
.then(result => {
console.log(result);
})
.catch(error => {
console.error(error);
});
I want to read the values of key, access, path, bucket and bucketPath and use them in the JSON file test.json.
I have a function that reads the content of configuration.js and attempts to write to test.json. Currently, I am able to write the values of bucket.I get the changed/new values and lines of null for the rest of the json.
I want to always return the new values and the other objects in the file. Also, in cases where bucket already has a value, I want it replaced by whatever is read from configuration.json
How can I fix this, and how can i change the values for the rest access, key, path and bucketpath?
index.js
const fs = require("fs").promises;
async function readJSON(filePath, values) {
const data = await fs.readFile(filePath);
try {
return JSON.parse(data);
} catch (err) {
console.log(err);
}
}
(async() => {
const credentials = await readJSON("./configuration.json");
const path = credentials.path;
const bucket = credentials.bucket;
const access = credentials.access;
const key = credentials.key;
const bucketPath = credentials.bucketPath;
const data = await jsonReader("./test.json");
const finalJSON = data.data ? .map((x) => {
if (x.type == "s3 credentials") return { ...x, bucket };
});
await fs.writeFile(
"./test.json",
JSON.stringify({
data: finalJSON
})
);
})();
test.json
{
"label": "storage record",
"data": [{
"id": "8902uw",
"type": "config",
"values": {
"access": "$access",
"key": "$key"
}
},
{
"id": "893wh002jei",
"type": "s3 credentials",
"bucket": ""
},
{
"id": "90yueps",
"type": "upload",
"input": "localhost: `$path`"
},
{
"id": "9028901",
"type": "change",
"name": "Adjust data",
"measure": [{
"t": "setter"
},
{
"p": "filename",
"to": "$join([\"$bucketPath\", data])"
}
],
"fixed": ""
}
]
}
configuration.json
{
"key": "880082",
"access": "793082",
"path": "/store",
"bucket": "testBucket",
"bucketPath": "/record"
}
Currently, when I run this, I get:
{
null,
"data": [{
null,
null,
null,
null
{
"id": "893wh002jei",
"type": "s3 credentials",
"bucket": ""
},
{
null,
null,
null
]
}
might this be a solution !
const fs = require('fs');
const fileName = './file.json';
const file = require(fileName);
file.key = "new value";
fs.writeFile(fileName, JSON.stringify(file), function writeJSON(err) {
if (err) return console.log(err);
console.log(JSON.stringify(file));
console.log('writing to ' + fileName);
});
[Updated answer]
From what you comment:
it's the same question. So when I run what I have, I get null for the other objects. I want test.json to remain the same just with updated values.
const testObj = await jsonReader("./test.json");
const finalJSON = {
...testObj,
data: testObj.data?.map((x) => {
if (x.type === 's3 credentials') {
return { ...x, bucket };
} else {
return x;
}
})
}
// which the code I gave above,
// the `finalJSON` now is the clone of the original from `test.json`
// plus updated values
await fs.writeFile(
"./test.json",
JSON.stringify(finalJSON)
);
[Original answer]
There is a problem with the function you pass to the map function.
The condition if without else.
I think you need else { return x; } to return original data if x.type is not what you expected.
I have the following NodeJs code in my AWS lambda as part of a larger lambda.
It calls an external API to return data regarding tournament schedules, I am able to get the response back from the API but I am unsure how to access the fields in the JSON response that I need.
This is my first time working with JS and NodeJS so I am unfamiliar with this.
const promise = new Promise((resolve, reject) => {
const options = {
host: 'MY_HOST',
path: 'MY_PATH',
headers: {
'key': 'value'
}
}
const req = https.get(options, res => {
let rawData = '';
res.on('data', chunk => {
rawData += chunk;
});
res.on('end', () => {
try {
resolve(JSON.parse(rawData));
} catch (err) {
reject(new Error(err));
}
});
});
req.on('error', err => {
reject(new Error(err));
});
});
// TODO - get promise result and iterate response
promise.then();
The response return is as follows (only showing first object for simplicity):
{
"_id": {
"$oid": "6346b02601a3c2111621c8e4"
},
"orgId": "1",
"year": "2023",
"schedule": [
{
"tournId": "464",
"name": "Fortinet Championship",
"timeZone": "America/Los_Angeles",
"date": {
"weekNumber": "37",
"start": {
"$date": {
"$numberLong": "1663200000000"
}
},
"end": {
"$date": {
"$numberLong": "1663459200000"
}
}
},
"format": "stroke",
"courses": [
{
"host": "Yes",
"location": {
"state": "CA",
"city": "Napa",
"country": "USA"
},
"courseName": "Silverado Resort and Spa (North Course)",
"courseId": "552"
}
],
"purse": {
"$numberInt": "8000000"
},
"winnersShare": {
"$numberInt": "1440000"
},
"fedexCupPoints": {
"$numberInt": "500"
}
}
]
}
The fields that I need access to are:
schedule[0].date.start
schedule[0].date.end
This is because I want to do e.g:
// loop each result and assert if current epoch is in the date Range
var currentTournamentId;
for(){
if(currentEpoch >= schedule.date.start && currentEpoch <= schedule.date.end) {
currentTournamentId = currentTournament.getId();
break;
}
}
How can I access these fields from the response?
Install body-parser andrequire it
let schedule = req.body.schedule;
schedule.forEach((item) => {
let start = item.date.start;
let end = item.date.end;
// do something
}
I have an Azure Function written in JS, which is triggered by the Service Bus and generates files to Blob Storage. When I'm trying to return an HTTP result I'm receiving the error as below:
System.Private.CoreLib: Exception while executing function: Functions.categoryMessageConsumer. Microsoft.Azure.WebJobs.Script: Unable to cast object of type 'System.String' to type 'Microsoft.AspNetCore.Http.HttpRequest'.
I don't know why the result is trying to be mapped to the HttpRequest object.
index.ts:
import { AzureFunction, Context, HttpRequest } from '#azure/functions';
...
const serviceBusTopicTrigger: AzureFunction = async function(context: Context, req: HttpRequest) {
let categoryMessage: CategoryMessage = Object.assign(new CategoryMessage(), req);
let messageValidationResult = await categoryMessage.validate();
if(!messageValidationResult.isValid) {
context.log.error(messageValidationResult.errors);
return {
status: 400,
body: "Unexpected error"
};
}
...
}
function.json output binding:
...
{
"type": "http",
"direction": "out",
"name": "$return"
}
...
host.json
{
"version": "2.0",
"logging": {
"applicationInsights": {
"samplingSettings": {
"isEnabled": true,
"excludedTypes": "Request"
}
}
},
"extensionBundle": {
"id": "Microsoft.Azure.Functions.ExtensionBundle",
"version": "[1.*, 2.0.0)"
}
}
var http = require('https');
module.exports = function (context, eventHubMessages) {
context.log(`JavaScript eventhub trigger function called for message array ${eventHubMessages}`);
eventHubMessages.forEach((message, index) => {
function callService(msg) {
let promise = new Promise((resolve, reject) => {
var options = {
host: process.env["HOST"],
port: process.env["PORT"],
path: process.env["PATH"],
method: process.env["WEBSERVICE_METHOD"],
headers: {
'Content-Type': process.env["WEBSERVICE_CONTENT_TYPE"],
'x-api-key' : process.env["WEBSERVICE_API_KEY"]
}
};
var response = '';
const request = http.request(options, (res) => {
res.on('data', (d) => {
response += d;
})
res.on('end', (d) => {
context.res = {
body: response
};
resolve(response);
})
});
request.on('error', (error) => {
context.log.error(error);
reject(error);
context.done();
})
request.write(msg);
request.end();
});
promise.then((response) => {
context.log(`mensagge send: ${msg}`);
context.log(`response: ${response}`);
context.done();
});
}
callService(message);
});
};
It was my index.js
and now it is my function.js:
{
"bindings": [
{
"type": "eventHubTrigger",
"name": "eventHubMessages",
"direction": "in",
"eventHubName": "event-hub-name",
"connection": "CONNECTION_EVENT_HUB",
"cardinality": "many",
"consumerGroup": "$Default",
"dataType": "string"
},
{
"type": "http",
"direction": "out",
"name": "$return"
}
]
}
and in the local.settings.json I declared all of the environment vars like HOST, PORT, CONNECTION_EVENT_HUB, etc.
This is because, your function is probably trying to create another object which it did not expect.
As you have mentioned the response variable name as $return and it is expecting that. Rather than this, code your function like below:
function.json:
{
"disabled": false,
"bindings": [
{
"authLevel": "function",
"type": "httpTrigger",
"direction": "in",
"name": "req"
},
{
"type": "http",
"direction": "out",
"name": "res"
}
]
}
JS code:
module.exports = function(context, req) {
context.log('Node.js HTTP trigger function processed a request. RequestUri=%s', req.originalUrl);
if (req.query.name || (req.body && req.body.name)) {
context.res = {
// status defaults to 200 */
body: "Hello " + (req.query.name || req.body.name)
};
}
else {
context.res = {
status: 400,
body: "Please pass a name on the query string or in the request body"
};
}
context.done();
};
For configuration options in function.json, you can visit here and here.
For us this was fixed by removing this binding from function.json:
{
"type": "http",
"direction": "out",
"name": "res"
}
So the result is if you're running the function using a timingTrigger you'd have:
{
"scriptFile": "index.js",
"bindings": [
{
"name": "myTimer",
"type": "timerTrigger",
"direction": "in",
"schedule": "0 */1 * * * *"
}
]
}
If you move back to HTTP or other you need to fill out the bindings in full again and remove the reference to the timer trigger:
{
"scriptFile": "index.js",
"bindings": [
{
"authLevel": "function",
"type": "httpTrigger",
"direction": "in",
"name": "req",
"methods": [
"get",
"post"
]
},
{
"type": "http",
"direction": "out",
"name": "res"
}
]
}
This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 3 years ago.
I am trying to fetch the attributes from the JSON.How to get the attribute url from the below JSON body?
I am receiving undefined in console
Here is my cloud function from
// shipmentai map tracking
exports.shipmentmaptracking = functions.https.onRequest((req, res) => {
var request = require("request");
var trackid = req.body.Tracking;
let d = {
"tracking_pages": [
{
"branded_tracking_theme_guid": "440bed90-617b-43ba-bd0e-31512ac66e23",
"tracking_number": "9400111699000367101815",
"carrier_code": "stamps_com",
"service_code": "usps_priority_mail",
}
]
};
var options = {
method: 'POST',
url: 'https://api.shipengine.com/v-beta/tracking_page',
headers: {
'Content-Type': 'application/json',
'api-key': 'Wyo4gpVIXfElQSDgF9p/L9aQ9kX3Um60X8hRSo8VAes'
},
body: JSON.stringify(d),
};
console.log('Sending a ' + options.method + ' request to ' + options.url);
request(options, function (error, response, body) {
console.log('Successfully received a response from ShipEngine')
if (error) {
console.log('An error was returned: ' + error.message);
res.status(500).send(error.message);
}
else if (response.statusCode >= 400) {
console.log('An error was returned: ' + response.statusCode + ' ' + response.statusMessage);
console.log(body);
res.status(response.statusCode).send(body);
}
else {
console.log('A successful response was returned');
console.log(body);
console.log(d.tracking_pages[0].url);
//res.status(200).send({'URL':shippp.tracking_pages[0].url});
console.log('statusCode:', response && response.statusCode);
}
});
});
Here is my Json output
How to fetch the attribute URL from the JSON below
{
"tracking_pages": [
{
"carrier_code": "stamps_com",
"tracking_number": "9400111699000367101815",
"branded_tracking_theme_guid": "440bed90-617b-43ba-bd0e-31512ac66e23",
"token": "l1XKcsYaEECc903KqBvtaA",
"url": "https://track.shipengine.com/se/v1/g/l1XKcsYaEECc903KqBvtaA",
"service_code": "usps_priority_mail"
}
],
"page": 0,
"pages": 0,
"total": 0
}
Thanks in advance
Simply get it from the data - note that I have given the entire object a name ("data") and that tracking_pages is an array - so you have to use the index number to get at it (assuming that there will be morethan one - otherwise there is no need to use an array) - and then its just the url property within that.
data.tracking_pages[0].url;
Obviously you will need a bit more sophistication in the selction - I's assuming that the actual data is more complex. And you can use JSON.parse() to convert the json o a regualr object.
But its just as simple as traversing the parents in the object and getting the selector correct.
let data = {
"tracking_pages": [
{
"carrier_code": "stamps_com",
"tracking_number": "9400111699000367101815",
"branded_tracking_theme_guid": "440bed90-617b-43ba-bd0e-31512ac66e23",
"token": "FmUfsOmjdEuioBuen1lMVA",
"url": "https://track.shipengine.com/se/v1/g/FmUfsOmjdEuioBuen1lMVA",
"service_code": "usps_priority_mail"
}
],
"page": 0,
"pages": 0,
"total": 0
}
let trackingUrl = data.tracking_pages[0].url;
console.log(trackingUrl) // gives https://track.shipengine.com/se/v1/g/FmUfsOmjdEuioBuen1lMVA
You can use . notation to access the url property in the object
var a={
"tracking_pages": [
{
"carrier_code": "stamps_com",
"tracking_number": "9400111699000367101815",
"branded_tracking_theme_guid": "440bed90-617b-43ba-bd0e-31512ac66e23",
"token": "FmUfsOmjdEuioBuen1lMVA",
"url": "https://track.shipengine.com/se/v1/g/FmUfsOmjdEuioBuen1lMVA",
"service_code": "usps_priority_mail"
}
],
"page": 0,
"pages": 0,
"total": 0
};
console.log(a.tracking_pages[0].url)
The expected output is not clear. If tracking_pages contain multiple url then you can use map to return an array of urls
let da = {
"tracking_pages": [{
"carrier_code": "stamps_com",
"tracking_number": "9400111699000367101815",
"branded_tracking_theme_guid": "440bed90-617b-43ba-bd0e-31512ac66e23",
"token": "FmUfsOmjdEuioBuen1lMVA",
"url": "https://track.shipengine.com/se/v1/g/FmUfsOmjdEuioBuen1lMVA",
"service_code": "usps_priority_mail"
}],
"page": 0,
"pages": 0,
"total": 0
}
let urlAr = da.tracking_pages.map(item => item.url);
console.log(urlAr)