Find all occurrences of JSON element using jQuery - javascript

How can you parse out all the values for a particular data point within a complex json response form a rest service call?
Here is my JQUERY code to get the rest service json response. I am looking to get all occurrences of "Id" for all "Approver" elements found in the json data and add them to delimited list - preferably using a
;
to separate each "Id"
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script><script>
$(document).ready(function(){
$("button").click(function(){
$.ajax({
type: 'GET',
url: 'MySite/Change/Request/12345/Approvals/GetApprovalGroupUsers?changeNumber=98765',
data: { get_param: 'value' },
dataType: 'json',
success: function (data) {
$.each(data, function(index, element) {
$('body').append($('<div>', {
text: element.Id
}));
});
}
});
});
});
</script>
</head>
<body>
<button>Click me to get listing of Id's</button>
</body>
</html>
The json data from the service in such:
{
"ApprovalSession": "3ebd4e73-7fc5-4113-9ccd-18833318ee09",
"LoadStatus": 0,
"Index": 0,
"ApprovalId": 0,
"Type": null,
"Approver": null,
"ApproverDisplay": null,
"Status": null,
"CreatedBy": null,
"CanBeRemoved": false,
"ConfigurationItems": [
"cigs01e4a002( OPERATING SYSTEM )",
"cigs01e4a002( OPERATING SYSTEM )",
"cigs01e4a004( OPERATING SYSTEM )",
"cigs01e4a004( OPERATING SYSTEM )"
],
"ApprovalReasons": [
{
"AssociatedCI": "abc4a002( OPERATING SYSTEM )",
"AssociatedRuleName": "Default Impact",
"AssociatedRuleApprovalType": null,
"AssociatedRulePartyType": "Targeted Group",
"AssociatedRulePartyName": "Operational Owner",
"AssociatedAdditionalComment": ""
},
{
"AssociatedCI": "xyza004( OPERATING SYSTEM )",
"AssociatedRuleName": "Default Impact ",
"AssociatedRuleApprovalType": null,
"AssociatedRulePartyType": "Targeted Group",
"AssociatedRulePartyName": "Technical Owner",
"AssociatedAdditionalComment": "Substitute Role"
}
],
"PossibleApprovers": [
{
"Approver": {
"Id": "Vzz436",
"Display": "some name",
"LineOfBusinessCode": "25",
"LineOfBusinessName": "Unix",
"LineOfBusinessHierarchy": null,
"PhoneNumber": "+123456789",
"RoleName": null,
"FullName": null,
"LineOfBusiness": null,
"ErrorMessage": null
},
"IsEscalation": false,
"IsDelegate": false
},
{
"Approver": {
"Id": "ppp71",
"Display": "more names",
"LineOfBusinessCode": "5",
"LineOfBusinessName": "Tech",
"LineOfBusinessHierarchy": null,
"PhoneNumber": "+987654321",
"RoleName": null,
"FullName": null,
"LineOfBusiness": null,
"ErrorMessage": null
},
"IsEscalation": false,
"IsDelegate": false
},
{
"Approver": {
"Id": "aaa5",
"Display": "mickey mouse",
"LineOfBusinessCode": "8",
"LineOfBusinessName": "Digital",
"LineOfBusinessHierarchy": null,
"PhoneNumber": "+87877676665",
"RoleName": null,
"FullName": null,
"LineOfBusiness": null,
"ErrorMessage": null
},
"IsEscalation": false,
"IsDelegate": false
}
],
"OriginalApprovals": [ ],
"AggregatedApproval": null,
"IsAggregated": false,
"AggregationId": 0,
"UpdatedBy": null,
"UpdatedDt": null,
"IsGroupActive": false
}

This is how you can get all ID's of the approvers, delimited by a semi-colon.
var data = {
"ApprovalSession": "3ebd4e73-7fc5-4113-9ccd-18833318ee09",
"LoadStatus": 0,
"Index": 0,
"ApprovalId": 0,
"Type": null,
"Approver": null,
"ApproverDisplay": null,
"Status": null,
"CreatedBy": null,
"CanBeRemoved": false,
"ConfigurationItems": [
"cigs01e4a002( OPERATING SYSTEM )",
"cigs01e4a002( OPERATING SYSTEM )",
"cigs01e4a004( OPERATING SYSTEM )",
"cigs01e4a004( OPERATING SYSTEM )"
],
"ApprovalReasons": [
{
"AssociatedCI": "abc4a002( OPERATING SYSTEM )",
"AssociatedRuleName": "Default Impact",
"AssociatedRuleApprovalType": null,
"AssociatedRulePartyType": "Targeted Group",
"AssociatedRulePartyName": "Operational Owner",
"AssociatedAdditionalComment": ""
},
{
"AssociatedCI": "xyza004( OPERATING SYSTEM )",
"AssociatedRuleName": "Default Impact ",
"AssociatedRuleApprovalType": null,
"AssociatedRulePartyType": "Targeted Group",
"AssociatedRulePartyName": "Technical Owner",
"AssociatedAdditionalComment": "Substitute Role"
}
],
"PossibleApprovers": [
{
"Approver": {
"Id": "Vzz436",
"Display": "some name",
"LineOfBusinessCode": "25",
"LineOfBusinessName": "Unix",
"LineOfBusinessHierarchy": null,
"PhoneNumber": "+123456789",
"RoleName": null,
"FullName": null,
"LineOfBusiness": null,
"ErrorMessage": null
},
"IsEscalation": false,
"IsDelegate": false
},
{
"Approver": {
"Id": "ppp71",
"Display": "more names",
"LineOfBusinessCode": "5",
"LineOfBusinessName": "Tech",
"LineOfBusinessHierarchy": null,
"PhoneNumber": "+987654321",
"RoleName": null,
"FullName": null,
"LineOfBusiness": null,
"ErrorMessage": null
},
"IsEscalation": false,
"IsDelegate": false
},
{
"Approver": {
"Id": "aaa5",
"Display": "mickey mouse",
"LineOfBusinessCode": "8",
"LineOfBusinessName": "Digital",
"LineOfBusinessHierarchy": null,
"PhoneNumber": "+87877676665",
"RoleName": null,
"FullName": null,
"LineOfBusiness": null,
"ErrorMessage": null
},
"IsEscalation": false,
"IsDelegate": false
}
],
"OriginalApprovals": [ ],
"AggregatedApproval": null,
"IsAggregated": false,
"AggregationId": 0,
"UpdatedBy": null,
"UpdatedDt": null,
"IsGroupActive": false
}
data.PossibleApprovers.forEach(function (approver) { document.write(approver.Approver.Id + ';')})

Related

How to Parse nested Json In Java script

I have this json in js,
and i am trying to get the key from the "Data" Object, like the SessionId and Email.
Please Help...
{
"HasError": false,
"Errors": [],
"ObjectName": "WebCheckoutCreateSessionResponse",
"Data": {
"HasError": false,
"ReturnCode": 0,
"ReturnMessage": null,
"SessionId": "abcde",
"SessionUrl": "https://pci.aaa.com/WebCheckout/Angular/Checkout.html#!/ZCreditWebCheckout/55cf7d1306b2bcc15d791dde524d2b4f616421172e6d75a013597c8dd2668843",
"RequestData": {
"Key": "ad",
"Local": "He",
"UniqueId": "<InvNo>1705</InvNo><InvYear>3102</InvYear><SugMismah>15</SugMismah><key>ad</key>",
"SuccessUrl": "",
"CancelUrl": "",
"CallbackUrl": "",
"PaymentType": "regular",
"CreateInvoice": false,
"AdditionalText": "",
"ShowCart": true,
"ThemeColor": "005ebb",
"Installments": {
"Type": "regular",
"MinQuantity": 1,
"MaxQuantity": 12
},
"Customer": {
"Email": "someone#gmail.com",
"Name": "Demo Client",
"PhoneNumber": "077-3233190",
"Attributes": {
"HolderId": "none",
"Name": "required",
"PhoneNumber": "required",
"Email": "optional"
}
},
"CartItems": [
{
"Amount": 117,
"Currency": "US",
"Name": "Danny ",
"Description": "Hi ",
"Quantity": 1,
"Image": "https://www.aaa.com/site/wp-content/themes/z-credit/img/decisions/decision2.png",
"IsTaxFree": false
}
],
"GetCurrencyCode": "376",
"BitButtonEnabled": true,
"MaxPayButtonEnabled": true,
"ApplePayButtonEnabled": true,
"GooglePayButtonEnabled": true,
"ShowTotalSumInPayButton": true
}
},
"ResponseType": 0
}
const population = JSON.parse(xhr.responseText);
for (const key in population) {
if (population.hasOwnProperty(key)) {
console.log(`${key}: ${population[key]}`);
}
}
You forgot to index the Data property.
const population = JSON.parse(xhr.responseText).Data;
for (const key in population) {
console.log(`${key}: ${population[key]}`);
}

Looping through nested JSON returns NULL

I'm trying to better understand how to work with nested JSON objects in JavaScript/React.
I am getting data through the GitLab API in the following form:
const merge_requests = [
{
"id": 39329289,
"iid": 156,
"project_id": 231,
"title": "Repaired some Links",
"description": "",
"state": "merged",
"created_at": "2022-12-03T12:22:14.690Z",
"updated_at": "2022-12-03T12:22:20.060Z",
"merged_by": {
"id": 1000,
"username": "test.user",
"name": "test.user#gmail.de",
"state": "active",
"avatar_url": "",
"web_url": ""
},
"merge_user": {
"id": 2802,
"username": "tes.user",
"name": "test.user#gmail.de",
"state": "active",
"avatar_url": "",
"web_url": ""
},
"merged_at": "2022-12-03T12:22:20.072Z",
"closed_by": null,
"closed_at": null,
"assignees": [],
"assignee": null,
"reviewers": [],
"source_project_id": 231,
"target_project_id": 231,
"labels": [],
"squash_commit_sha": null,
"discussion_locked": null,
"should_remove_source_branch": null,
"force_remove_source_branch": null,
"reference": "!156",
"references": {
"short": "!156",
"relative": "!156",
"full": ""
},
"web_url": "",
"time_stats": {
"time_estimate": 0,
"total_time_spent": 0,
"human_time_estimate": null,
"human_total_time_spent": null
},
"squash": false,
"task_completion_status": {
"count": 0,
"completed_count": 0
},
"has_conflicts": false,
"blocking_discussions_resolved": true,
"approvals_before_merge": null
},
{
"id": 39329289,
"iid": 156,
"project_id": 231,
"title": "Repaired some Links",
"description": "",
"state": "merged",
"created_at": "2022-12-03T12:22:14.690Z",
"updated_at": "2022-12-03T12:22:20.060Z",
"merged_by": {
"id": 1000,
"username": "test.user",
"name": "test.user#gmail.de",
"state": "active",
"avatar_url": "",
"web_url": ""
},
"merge_user": {
"id": 2802,
"username": "test.user",
"name": "test.user#gmail.de",
"state": "active",
"avatar_url": "",
"web_url": ""
},
"merged_at": "2022-12-03T12:22:20.072Z",
"closed_by": null,
"closed_at": null,
"assignees": [],
"assignee": null,
"reviewers": [],
"source_project_id": 231,
"target_project_id": 231,
"labels": [],
"squash_commit_sha": null,
"discussion_locked": null,
"should_remove_source_branch": null,
"force_remove_source_branch": null,
"reference": "!156",
"references": {
"short": "!156",
"relative": "!156",
"full": ""
},
"web_url": "",
"time_stats": {
"time_estimate": 0,
"total_time_spent": 0,
"human_time_estimate": null,
"human_total_time_spent": null
},
"squash": false,
"task_completion_status": {
"count": 0,
"completed_count": 0
},
"has_conflicts": false,
"blocking_discussions_resolved": true,
"approvals_before_merge": null
},]
I want to loop through all objects(merge requests) in this JSON and create a new array with the merge_user.name.
console.log(merge_requests[0].merge_user.name);
console.log(merge_requests[1].merge_user.name);
The logs above return both the correct values. However, I cannot loop through the JSON to create a new array from the data like this:
const arrTest = [];
for(var i = 0; i < Object.keys(merge_requests).length; i++)
{
var mergeUserName = merge_requests[i].merge_user.name;
arrTest.push(mergeUserName);
}
console.log(arrTest);
}
The code above leads to the following error: Uncaught (in promise) TypeError: resultData[i].merge_user is null
Here is a picture:
I am currently learning JS coming from R. I have huge problems working with JSON instead of dataframes and I cannot find any documentation to learn from. I would appreciated any advice/ sources.
const arrTest = [];
for(var i = 0; i < merge_requests.length; i++){
let mergeUserName = merge_requests[i].merge_user?.name;
arrTest.push(mergeUserName);
}
console.log(arrTest);
merge_requests[i].merge_user?.name will return undefined if object is not present in the json.
There is no need to use Object.keys(),you can use merge_requests.length directly
const arrTest = [];
for(var i = 0; i < merge_requests.length; i++){
let mergeUserName = merge_requests[i].merge_user.name;
arrTest.push(mergeUserName);
}
console.log(arrTest);
const merge_requests = [
{
"id": 39329289,
"iid": 156,
"project_id": 231,
"title": "Repaired some Links",
"description": "",
"state": "merged",
"created_at": "2022-12-03T12:22:14.690Z",
"updated_at": "2022-12-03T12:22:20.060Z",
"merged_by": {
"id": 1000,
"username": "test.user",
"name": "test.user#gmail.de",
"state": "active",
"avatar_url": "",
"web_url": ""
},
"merge_user": {
"id": 2802,
"username": "tes.user",
"name": "test.user#gmail.de",
"state": "active",
"avatar_url": "",
"web_url": ""
},
"merged_at": "2022-12-03T12:22:20.072Z",
"closed_by": null,
"closed_at": null,
"assignees": [],
"assignee": null,
"reviewers": [],
"source_project_id": 231,
"target_project_id": 231,
"labels": [],
"squash_commit_sha": null,
"discussion_locked": null,
"should_remove_source_branch": null,
"force_remove_source_branch": null,
"reference": "!156",
"references": {
"short": "!156",
"relative": "!156",
"full": ""
},
"web_url": "",
"time_stats": {
"time_estimate": 0,
"total_time_spent": 0,
"human_time_estimate": null,
"human_total_time_spent": null
},
"squash": false,
"task_completion_status": {
"count": 0,
"completed_count": 0
},
"has_conflicts": false,
"blocking_discussions_resolved": true,
"approvals_before_merge": null
},
{
"id": 39329289,
"iid": 156,
"project_id": 231,
"title": "Repaired some Links",
"description": "",
"state": "merged",
"created_at": "2022-12-03T12:22:14.690Z",
"updated_at": "2022-12-03T12:22:20.060Z",
"merged_by": {
"id": 1000,
"username": "test.user",
"name": "test.user#gmail.de",
"state": "active",
"avatar_url": "",
"web_url": ""
},
"merge_user": {
"id": 2802,
"username": "test.user",
"name": "test.user#gmail.de",
"state": "active",
"avatar_url": "",
"web_url": ""
},
"merged_at": "2022-12-03T12:22:20.072Z",
"closed_by": null,
"closed_at": null,
"assignees": [],
"assignee": null,
"reviewers": [],
"source_project_id": 231,
"target_project_id": 231,
"labels": [],
"squash_commit_sha": null,
"discussion_locked": null,
"should_remove_source_branch": null,
"force_remove_source_branch": null,
"reference": "!156",
"references": {
"short": "!156",
"relative": "!156",
"full": ""
},
"web_url": "",
"time_stats": {
"time_estimate": 0,
"total_time_spent": 0,
"human_time_estimate": null,
"human_total_time_spent": null
},
"squash": false,
"task_completion_status": {
"count": 0,
"completed_count": 0
},
"has_conflicts": false,
"blocking_discussions_resolved": true,
"approvals_before_merge": null
}]
const arrTest = [];
for(var i = 0; i < merge_requests.length; i++){
let mergeUserName = merge_requests[i].merge_user.name;
arrTest.push(mergeUserName);
}
console.log(arrTest);
I copy & pasted your code & JSON and it works fine.
Make sure your JSON is parsed after getting it from ate API typeof merge_requests should return object, if it returns string then do the following:
const parsedData = JSON.parse(merge_requests) and loop through parsedData
i checked your code it's working fine.
Check your api request, are you sure you waiting for it till it get fulfilled?

How can i convert a JSON array payload into one object with specific fields and an array with dates?

I have a JSON payload fetched from the backend. The data contains an payload array with objects. By some how i want to convert these objects inside the array to one object, and the selectedDate dates to own array. The JSON payload seems like this:
{
"success": true,
"payload": [
{
"weekNumber": 40,
"sortOrder": 1,
"label": "autumn",
"numberOfPossibleDays": 3,
"editable": true,
"selectedDate": "2020-09-29",
"deliveryDays": [
{
"date": "2020-09-28",
"contactPerson": null,
"phoneNumber": null,
"contactPerson2": null,
"phoneNumber2": null,
"selected": false
},
{
"date": "2020-09-29",
"contactPerson": "John",
"phoneNumber": "99887744",
"contactPerson2": "Tom",
"phoneNumber2": "40040000,
"selected": true
},
{
"date": "2020-09-30",
"contactPerson": null,
"phoneNumber": null,
"contactPerson2": null,
"phoneNumber2": null,
"selected": false
}
]
},
{
"weekNumber": 53,
"sortOrder": 2,
"label": "christmas",
"numberOfPossibleDays": 2,
"editable": true,
"selectedDate": "2020-12-29",
"deliveryDays": [
{
"date": "2020-12-28",
"contactPerson": null,
"phoneNumber": null,
"contactPerson2": null,
"phoneNumber2": null,
"selected": false
},
{
"date": "2020-12-29",
"contactPerson": "Doe,
"phoneNumber": "99999999",
"contactPerson2": "Foo",
"phoneNumber2": "44552200",
"selected": true
}
]
}
]
}
What i want to do is to get output objects like this:
{
autumn=firstContactPersonName: "John",
autumn=firstContactPersonPhone: "46442644",
autumn=secondContactPersonName: "Tom",
autumn=secondContactPersonPhone: "40040000"
christmas=firstContactPersonName: "Doe",
christmas=firstContactPersonPhone: "99999999",
christmas=secondContactPersonName: "Foo",
christmas=secondContactPersonPhone: "44552200"
}
And the dates output should be an array like this:
const dateArray = ["autumn=2020-09-29", "christmas=2020-12-29"]
I want it to be dynamically, because sometimes i might be have a object for easter and so on. Why i want to do this is because I am using the object to populate content in the input fields and the dateArray to enable which dates is choosen. I know this is not the best solution, but i have to try to make it out this way.
I am all new to JavaScript and i have some problems making it out. I would appreciate if anyone can help me out, please? I hope the question and the example is good. Thank you for the help.
let obj = {
"success": true,
"payload": [
{
"weekNumber": 40,
"sortOrder": 1,
"label": "autumn",
"numberOfPossibleDays": 3,
"editable": true,
"selectedDate": "2020-09-29",
"deliveryDays": [
{
"date": "2020-09-28",
"contactPerson": null,
"phoneNumber": null,
"contactPerson2": null,
"phoneNumber2": null,
"selected": false
},
{
"date": "2020-09-29",
"contactPerson": "John",
"phoneNumber": "99887744",
"contactPerson2": "Tom",
"phoneNumber2": "40040000",
"selected": true
},
{
"date": "2020-09-30",
"contactPerson": null,
"phoneNumber": null,
"contactPerson2": null,
"phoneNumber2": null,
"selected": false
}
]
},
{
"weekNumber": 53,
"sortOrder": 2,
"label": "christmas",
"numberOfPossibleDays": 2,
"editable": true,
"selectedDate": "2020-12-29",
"deliveryDays": [
{
"date": "2020-12-28",
"contactPerson": null,
"phoneNumber": null,
"contactPerson2": null,
"phoneNumber2": null,
"selected": false
},
{
"date": "2020-12-29",
"contactPerson": "Doe",
"phoneNumber": "99999999",
"contactPerson2": "Foo",
"phoneNumber2": "44552200",
"selected": true
}
]
}
]
}
let results={};
let datesArray=[];
obj.payload.map((x)=>{
datesArray.push(x.label+"="+x.selectedDate);
x["deliveryDays"].map((y)=>{
if(y.contactPerson){
let personKey = x.label + "=firstContactPersonName";
results[personKey] = y.contactPerson;
let contactKey = x.label+"=firstContactPersonPhone";
results[contactKey] = y.phoneNumber;
}
if(y.contactPerson2){
let secondPersonKey = x.label + "=secondContactPersonName";
results[secondPersonKey] = y.contactPerson2;
let secondContactKey = x.label+"=secondContactPersonPhone";
results[secondContactKey] = y.phoneNumber2;
}
});
});
console.log(datesArray)
console.log(results)
We iterate throught payload and make use of dates array to store the dates and results array to obtain the first and second contact person names during a season. Hope this helps!

Get fee amount from Braintree Transaction.search()

Is it possible to get the Braintree fee amount while searching for transactions using Transaction.search() method? I specifically use
Braintree Node.js SDK API, so when I call the method:
const gateway = braintree.connect({
environment: braintree.Environment.Production,
merchantId : process.env.BRAINTREE_merchantId,
publicKey : process.env.BRAINTREE_publicKey,
privateKey : process.env.BRAINTREE_privateKey,
});
// start and end are well formatted dates, irrelevant here
const stream = gateway.transaction.search((search) => {
search.createdAt().between(start, end)
});
let result = [];
stream.on("data", (transaction) => {
result.push(transaction);
});
stream.on("end", () => {
console.log(result[0]);
});
stream.on("error", reject);
stream.resume();
My console.log(result[0]) shows pretty big (160 lines of code) single transaction object, where transaction.serviceFeeAmount: null.
console.log({
"id": "1egncjr5",
"status": "settled",
"type": "sale",
"currencyIsoCode": "EUR",
"amount": "799.00",
"merchantAccountId": "mycompanyEUR",
"subMerchantAccountId": null,
"masterMerchantAccountId": null,
"orderId": "54144",
"createdAt": "2018-03-07T08:55:09Z",
"updatedAt": "2018-03-07T19:41:10Z",
"customer": {
"id": null,
"firstName": null,
"lastName": null,
"company": "Kunlabora NV",
"email": "client#email.com",
"website": null,
"phone": null,
"fax": null
},
"billing": {
"id": null,
"firstName": null,
"lastName": null,
"company": "Kunlabora NV",
"streetAddress": "Veldkant 33 A",
"extendedAddress": null,
"locality": "Kontich",
"region": null,
"postalCode": "2550",
"countryName": "Belgium",
"countryCodeAlpha2": "BE",
"countryCodeAlpha3": "BEL",
"countryCodeNumeric": "056"
},
"refundId": null,
"refundIds": [],
"refundedTransactionId": null,
"partialSettlementTransactionIds": [],
"authorizedTransactionId": null,
"settlementBatchId": "2018-03-08_mycompanyEUR_ecwhvhcf",
"shipping": {
"id": null,
"firstName": null,
"lastName": null,
"company": null,
"streetAddress": null,
"extendedAddress": null,
"locality": null,
"region": null,
"postalCode": null,
"countryName": null,
"countryCodeAlpha2": null,
"countryCodeAlpha3": null,
"countryCodeNumeric": null
},
"customFields": "",
"avsErrorResponseCode": null,
"avsPostalCodeResponseCode": "U",
"avsStreetAddressResponseCode": "U",
"cvvResponseCode": "M",
"gatewayRejectionReason": null,
"processorAuthorizationCode": "735709",
"processorResponseCode": "1000",
"processorResponseText": "Approved",
"additionalProcessorResponse": null,
"voiceReferralNumber": "",
"purchaseOrderNumber": null,
"taxAmount": "0.00",
"taxExempt": false,
"creditCard": {
"token": null,
"bin": "CENSORED",
"last4": "CENSODER",
"cardType": "MasterCard",
"expirationMonth": "CENSORED",
"expirationYear": "CENSORED",
"customerLocation": "CENSORED",
"cardholderName": "",
"imageUrl": "https://assets.braintreegateway.com/payment_method_logo/mastercard.png?environment=production",
"prepaid": "No",
"healthcare": "No",
"debit": "No",
"durbinRegulated": "No",
"commercial": "No",
"payroll": "No",
"issuingBank": "BNP PARIBAS FORTIS",
"countryOfIssuance": "BEL",
"productId": "MCB",
"uniqueNumberIdentifier": null,
"venmoSdk": false,
"maskedNumber": "CENSORED",
"expirationDate": "04/2020"
},
"statusHistory": [
{
"timestamp": "2018-03-07T08:55:10Z",
"status": "authorized",
"amount": "799.00",
"user": "office#mycompany.com",
"transactionSource": "api"
},
{
"timestamp": "2018-03-07T08:55:10Z",
"status": "submitted_for_settlement",
"amount": "799.00",
"user": "office#mycompany.com",
"transactionSource": "api"
},
{
"timestamp": "2018-03-07T19:41:10Z",
"status": "settled",
"amount": "799.00",
"user": null,
"transactionSource": ""
}
],
"planId": null,
"subscriptionId": null,
"subscription": {
"billingPeriodEndDate": null,
"billingPeriodStartDate": null
},
"addOns": [],
"discounts": [],
"descriptor": {
"name": null,
"phone": null,
"url": null
},
"recurring": false,
"channel": "woocommerce_bt",
"serviceFeeAmount": null,
"escrowStatus": null,
"disbursementDetails": {
"disbursementDate": null,
"settlementAmount": null,
"settlementCurrencyIsoCode": null,
"settlementCurrencyExchangeRate": null,
"fundsHeld": null,
"success": null
},
"disputes": [],
"authorizationAdjustments": [],
"paymentInstrumentType": "credit_card",
"processorSettlementResponseCode": "",
"processorSettlementResponseText": "",
"threeDSecureInfo": null,
"shipsFromPostalCode": null,
"shippingAmount": null,
"discountAmount": null,
"paypalAccount": {},
"coinbaseAccount": {},
"applePayCard": {},
"androidPayCard": {},
"visaCheckoutCard": {},
"masterpassCard": {}
})
Question: How do I get the transaction fee here?
You might find it in transactionFeeAmount field
This is the answer I received from Braintree support team:
Unfortunately no it is not possible to search for the Braintree fee amount using the API at this time (meaning 14/05/2018).
You can calculate the fees for individual transactions by performing an Advanced Transaction Search.
Log into the Control Panel
Under Advanced Search, click Transactions
Uncheck the box next to Creation date range
Check the box next to Disbursed date range
Choose your desired date range
Click Search
On the results page, click Download
Open the CSV file in the spreadsheet program of your choice
From here, you can create additional columns for your transaction fees. To find your specific transaction fees, look at the Pricing Schedule on your statement. Make sure to round down, and then apply the fees to your individual transactions.
So it looks like I am going to implement some PhantomJS module to do just that.

Getting a variable from a multidimentional JSON array using Jquery

I am retrieving a multidimensional JSON array using JQUERY.
I need to print out various items from the array, but am having a hard time figuring out how to go through the array and get these items so I can insert them into the HTML.
Here is an example of the array (this is what is taken from the jsonpage.php referenced below.
{
"count":1,
"total_count":1,
"contacts":[
{
"id":92840643,
"user_id":55536,
"first_name":"John",
"last_name":"Doe",
"full_name":"John Doe",
"initials":"JD",
"title":null,
"company":null,
"email":"john#doe.com",
"avatar":"https://graph.facebook.com/123454/picture?type=large",
"avatar_url":"https://graph.facebook.com/123454/picture?type=large",
"last_contacted":null,
"visible":true,
"twitter":null,
"facebook_url":null,
"linkedin_url":null,
"first_contacted":null,
"created_at":"2014-05-26T19:06:55Z",
"updated_at":"2014-05-26T19:12:42Z",
"hits":0,
"user_bucket_id":486405,
"team_parent_id":null,
"snoozed_at":null,
"snooze_days":null,
"groupings":[
{
"id":21554286,
"type":"Grouping::Location",
"name":"Johnson, NY",
"stub":"frisco tx",
"bucket_id":null,
"user_id":55536,
"domain_id":null,
"editable":null,
"conversable":null,
"locked":null,
"derived_from_id":null
},
{
"id":21553660,
"type":"Grouping::Bucket",
"name":"Top Customers",
"stub":"top customers",
"bucket_id":486405,
"user_id":55536,
"domain_id":null,
"editable":null,
"conversable":null,
"locked":null,
"derived_from_id":null,
"has_followups":true,
"num_days_to_followup":30,
"program_id":null
}
],
"email_addresses":[
"john#doe.com"
],
"tags":[
],
"contact_status":3,
"team_last_contacted":null,
"team_last_contacted_by":null,
"phone_numbers":[
],
"addresses":[
{
"_id":"538390cfcc0fb067d8000353",
"created_at":"2014-05-26T19:06:55Z",
"deleted_at":null,
"extra_data":{
"address_city":"Johnson",
"address_state":"NY",
"address_country":"United States"
},
"label":"Address",
"primary":null,
"remote_id":null,
"updated_at":"2014-05-26T19:06:55Z",
"username":null,
"value":"Johnson, NY\nUnited States"
}
],
"social_profiles":[
],
"websites":[
],
"custom_fields":[
{
"_id":"538390cfcc0fb067d8000354",
"custom_field_id":46639,
"deleted_at":null,
"label":"WeeklyNews",
"value":"YES"
},
{
"_id":"538390cfcc0fb067d8000355",
"custom_field_id":46640,
"deleted_at":null,
"label":"Current Credits",
"value":"142"
},
{
"_id":"538390cfcc0fb067d8000356",
"custom_field_id":46641,
"deleted_at":null,
"label":"Total Purchased Amount",
"value":"400"
},
{
"_id":"538390cfcc0fb067d8000357",
"custom_field_id":46642,
"deleted_at":null,
"label":"VDownloads",
"value":"112"
},
{
"_id":"538390cfcc0fb067d8000358",
"custom_field_id":46643,
"deleted_at":null,
"label":"AEDownloads",
"value":"9"
},
{
"_id":"538390cfcc0fb067d8000359",
"custom_field_id":46644,
"deleted_at":null,
"label":"ADownloads",
"value":"53"
},
{
"_id":"538390cfcc0fb067d800035a",
"custom_field_id":46638,
"deleted_at":null,
"label":"Last Login",
"value":"2014-05-25 23:14:19"
},
{
"_id":"538390cfcc0fb067d800035b",
"custom_field_id":46649,
"deleted_at":null,
"label":"Label",
"value":"Group1"
}
]
}
]
}
And here is the jquery success code:
$.post('/jsonpage.php', post_data, function(response) {
});
Now, if I put alert(response); within the function i.e.:
$.post('/jsonpage.php', post_data, function(response) {
alert(response);
});
Then, it 'does' alert the entire JSON string as listed above.
However, if I put this:
$.post('/jsonpage.php', post_data, function(response) {
alert(response.count);
});
Then, I get UNDEFINED in the alert box. I have tried a few different variables to 'alert' and they all come back undefined.
Thanks for your help!
Craig
response.total_count
response.contacts[0].id
response.contacts[0].groupings[0].stub
And so on.
Here are some ways of using the data in your json response. Hope it helps.
$.post('/jsonpage.php', post_data, function(response) {
if (!response.contacts || !response.contacts.length) {
alert("Error loading that/those contact(s)");
return;
}
for (var i=0, c; c = response.contacts[i]; i++) {
// c is each contact, do stuff with c
alert("That contact was created at " + c.created_at + " and last updated at " + c.updated_at);
var cities = [];
for (var j=0, a; a = c.addresses[j]; j++) {
// a refers to each address
cities.push(a.extra_data.address_city);
}
alert(c.full_name + " lives in " + cities.join(" and ") + ".");
for (var j=0, cf; cf = c.custom_fields[j]; j++) {
// cf is each custom_field
// build a form or something
// element label is cf.label
// element value is currently cf.value
var p = document.createElement("p");
p.appendChild(document.createTextNode(cf.label));
var el = document.createElement("input");
el.type = "text";
el.value = cf.value;
p.appendChild(el);
document.getElementById("someForm").appendChild(p);
}
}
});
Try this
var data = { "count": 1, "total_count": 1, "contacts": [{ "id": 92840643, "user_id": 55536, "first_name": "John", "last_name": "Doe", "full_name": "John Doe", "initials": "JD", "title": null, "company": null, "email": "john#doe.com", "avatar": "https://graph.facebook.com/123454/picture?type=large", "avatar_url": "https://graph.facebook.com/123454/picture?type=large", "last_contacted": null, "visible": true, "twitter": null, "facebook_url": null, "linkedin_url": null, "first_contacted": null, "created_at": "2014-05-26T19:06:55Z", "updated_at": "2014-05-26T19:12:42Z", "hits": 0, "user_bucket_id": 486405, "team_parent_id": null, "snoozed_at": null, "snooze_days": null, "groupings": [{ "id": 21554286, "type": "Grouping::Location", "name": "Johnson, NY", "stub": "frisco tx", "bucket_id": null, "user_id": 55536, "domain_id": null, "editable": null, "conversable": null, "locked": null, "derived_from_id": null }, { "id": 21553660, "type": "Grouping::Bucket", "name": "Top Customers", "stub": "top customers", "bucket_id": 486405, "user_id": 55536, "domain_id": null, "editable": null, "conversable": null, "locked": null, "derived_from_id": null, "has_followups": true, "num_days_to_followup": 30, "program_id": null}], "email_addresses": ["john#doe.com"], "tags": [], "contact_status": 3, "team_last_contacted": null, "team_last_contacted_by": null, "phone_numbers": [], "addresses": [{ "_id": "538390cfcc0fb067d8000353", "created_at": "2014-05-26T19:06:55Z", "deleted_at": null, "extra_data": { "address_city": "Johnson", "address_state": "NY", "address_country": "United States" }, "label": "Address", "primary": null, "remote_id": null, "updated_at": "2014-05-26T19:06:55Z", "username": null, "value": "Johnson, NY\nUnited States"}], "social_profiles": [], "websites": [], "custom_fields": [{ "_id": "538390cfcc0fb067d8000354", "custom_field_id": 46639, "deleted_at": null, "label": "WeeklyNews", "value": "YES" }, { "_id": "538390cfcc0fb067d8000355", "custom_field_id": 46640, "deleted_at": null, "label": "Current Credits", "value": "142" }, { "_id": "538390cfcc0fb067d8000356", "custom_field_id": 46641, "deleted_at": null, "label": "Total Purchased Amount", "value": "400" }, { "_id": "538390cfcc0fb067d8000357", "custom_field_id": 46642, "deleted_at": null, "label": "VDownloads", "value": "112" }, { "_id": "538390cfcc0fb067d8000358", "custom_field_id": 46643, "deleted_at": null, "label": "AEDownloads", "value": "9" }, { "_id": "538390cfcc0fb067d8000359", "custom_field_id": 46644, "deleted_at": null, "label": "ADownloads", "value": "53" }, { "_id": "538390cfcc0fb067d800035a", "custom_field_id": 46638, "deleted_at": null, "label": "Last Login", "value": "2014-05-25 23:14:19" }, { "_id": "538390cfcc0fb067d800035b", "custom_field_id": 46649, "deleted_at": null, "label": "Label", "value": "Group1"}]}] };
alert(data["contacts"][0]["id"]);
//get count
alert(data["count"]); //1
//get first contacts data
data["contacts"][0]["id"] //retruns 92840643
//do same for others to get data

Categories

Resources