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)
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);
});
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 2 years ago.
I'm trying to build a simple web app using JQuery. I'm trying to make an ajax request to the server the following way:
function getClients() {
return $.ajax('/api/v1/clients',
{
headers: {
Authorization: 'Token ' + getCookie("auth_token")
}
});
}
I also do the following:
$(document).ready(function() {
console.log(getClients());
});
So that I can see the result of my request. In the console I see the following:
{
"readyState": 4,
"responseText": "{\"count\":2,\"next\":null,\"previous\":null,\"results\":[{\"id\":2,\"group_set\":[1],\"first_name\":\"b\",\"last_name\":\"b\",\"username\":\"b\",\"telegram_id\":null,\"phone\":null,\"picture\":null,\"blocked\":false,\"telegram_user\":null,\"user\":2,\"source\":null},{\"id\":1,\"group_set\":[1],\"first_name\":\"a\",\"last_name\":\"a\",\"username\":\"a\",\"telegram_id\":null,\"phone\":null,\"picture\":null,\"blocked\":false,\"telegram_user\":null,\"user\":2,\"source\":null}]}",
"responseJSON": {
"count": 2,
"next": null,
"previous": null,
"results": [
{
"id": 2,
"group_set": [
1
],
"first_name": "b",
"last_name": "b",
"username": "b",
"telegram_id": null,
"phone": null,
"picture": null,
"blocked": false,
"telegram_user": null,
"user": 2,
"source": null
},
{
"id": 1,
"group_set": [
1
],
"first_name": "a",
"last_name": "a",
"username": "a",
"telegram_id": null,
"phone": null,
"picture": null,
"blocked": false,
"telegram_user": null,
"user": 2,
"source": null
}
]
},
"status": 200,
"statusText": "OK"
}
(This output is made by clicking on "Copy object" in Firefox).
However, if I change getClients() as shown below:
function getClients() {
return $.ajax('/api/v1/clients',
{
headers: {
Authorization: 'Token ' + getCookie("auth_token")
}
}).responseJSON;
}
Then in the console I will get
undefined
Also, when I try to use the object's properties in code, I get an error that the properties are undefined.
How is that and how do I fix this?
Thank you.
getClients returns promise. Your code:
return $.ajax(...).responseJSON
reads responseJSON from promise object which is undefined. Promise returns result only when it is resolved (then())
You should leave getClients as is and change part in document ready like:
$(document).ready(function() {
getClients().then(function(response) {
const respJson = JSON.parse(response);
console.log(respJson.responseJSON);
});
})
Keep the getClients() function as seen below:
function getClients() {
return $.ajax('/api/v1/clients',
{
headers: {
Authorization: 'Token ' + getCookie("auth_token")
}
});
}
Then use Bracket Notation to select properties:
var clientData = getClients();
var jsonData = clientData["responseJSON"];
var results = jsonData["results"];
console.log(results[0]["first_name"]); // Logs the "first_name" value from first results array
Since your JSON properties are strings, Bracket Notation is required. Otherwise, you could use, for example: clientData.responseJSON
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);
}
};
I need help replacing data inside of a JSON file using NODE.JS. My current method adds it with the same ID which is correct. However, when the data is received back, it drops the last duplicate because it found the old value first. I think what I really need to do is select JSON element by ID. Then replace it with the new.
Here is my AJAX request:
putComment: function(commentJSON, success, error) {
$.ajax({
type: 'post',
url: 'http://localhost:8080',
data: JSON.stringify(commentJSON),
success: function(comment) {
success(comment)
},
error: error
});
},
Here's my NODE:
if (req.method == 'POST') {
req.on('data', function(chunk) {
var element = JSON.parse(chunk);
fs.readFile("comments-data.json", 'utf8', function(err, json) {
var array = JSON.parse(json);
array.push(element);
fs.writeFile("comments-data.json", JSON.stringify(array), function(err) {
if (err) {
console.log(err);
return;
}
console.log("The file was saved!");
});
});
res.end('{"msg": "success"}');
});
};
Here is the data with duplicate id's:
[
{
"id": "c1",
"parent": null,
"created": "2016-08-12T19:57:21.282Z",
"modified": "2016-08-12T19:57:21.282Z",
"content": "test",
"fullname": "John Clark",
"profile_picture_url": "https://viima-app.s3.amazonaws.com/media/user_profiles/user-icon.png",
"created_by_current_user": true,
"upvote_count": 0,
"user_has_upvoted": false
},
{
"id": "c1",
"parent": null,
"created": "2016-08-12T19:57:21.282Z",
"modified": 1471031853696,
"content": "test 123",
"fullname": "John Clark",
"profile_picture_url": "https://viima-app.s3.amazonaws.com/media/user_profiles/user-icon.png",
"created_by_current_user": true,
"upvote_count": 0,
"user_has_upvoted": false
}
]
Are you just trying to replace the item if it exists? If so, you could do something like this:
var array = JSON.parse(json);
var isNew = true;
for (var i = 0; i < array.length; i++) {
if (array[i].id === element.id) {
array[i] = element;
isNew = false;
break;
}
}
//doesn't exist yet
if (isNew) {
array.push(element);
}
fs.writeFile("comments-data.json", JSON.stringify(array), function(err) {
if (err) {
console.log(err);
return;
}
console.log("The file was saved!");
});
I am making a web app for nokia S40 platform . I am calling a web service using Javascript that returns the Following JSON
{ "status_code": 200, "status_txt": "OK", "data": { "expand": [ { "short_url": "http:\/\/bit.ly\/msapps", "long_url": "http:\/\/www.microsoft.com\/web\/gallery\/?wt.mc_id=soc-in-wag-msp-M389", "user_hash": "gbL9jV", "global_hash": "eHgpGh" } ] } }
I want to obtain the "short_url" and "long_url " values
I am using eval as var obj = eval ("(" + xmlhttp.responseText + ")");
where xmlhttp.responseText conatains the JSON response.
Please help
tried this and worked
var s = '{ "status_code": 200, "status_txt": "OK", "data": { "expand": [ { "short_url": "http://bit.ly/msapps", "long_url": "http://www.microsoft.com/web/gallery/?wt.mc_id=soc-in-wag-msp-M389", "user_hash": "gbL9jV", "global_hash": "eHgpGh" } ] } } '
var d = JSON.parse(s);
console.log(d.data.expand[0].short_url);
console.log(d.data.expand[0].long_url);
This expression
JSON.parse('{ "status_code": 200, "status_txt": "OK", "data": { "expand": [ { "short_url": "http:\/\/bit.ly\/msapps", "long_url": "http:\/\/www.microsoft.com\/web\/gallery\/?wt.mc_id=soc-in-wag-msp-M389", "user_hash": "gbL9jV", "global_hash": "eHgpGh" } ] } }').data.expand[0].short_url
returns "http://bit.ly/msapps"
How about this
var json = "{}" // Your JSON string
json = new Function('return ' + json)();
console.log(json.data.expand[0].short_url, json.data.expand[0].long_url);