How to use this json with angular datatables - javascript

This is my server response.
{
"status": "success",
"data": [{
"id": null,
"reportType": "Total Voucher Report",
"reportModule": "Vouchers",
"reportData": [{
"id": "1",
"voucherPackId": "2",
"serialNumber": "0",
"status": "Free",
"isBlocked": "N",
"voucherPin": "0",
"buyDate": null,
"redeemDate": null,
"phoneNumber": null,
"statusCode": null,
"identifier": "MCM0007532",
"merchantName": "test1",
"voucherName": "fddf",
"expiryDate": "2016-02-24 00:00:00",
"dealCategory": "Hotels \u0026 Travel",
"shortDescription": "xvxv",
"voucherWorth": "33.00"
}, {
"id": "2",
"voucherPackId": "2",
"serialNumber": "0",
"status": "Free",
"isBlocked": "N",
"voucherPin": "0",
"buyDate": null,
"redeemDate": null,
"phoneNumber": null,
"statusCode": null,
"identifier": "MCM0007532",
"merchantName": "test1",
"voucherName": "fddf",
"expiryDate": "2016-02-24 00:00:00",
"dealCategory": "Hotels \u0026 Travel",
"shortDescription": "xvxv",
"voucherWorth": "33.00"
}, {
"id": "3",
"voucherPackId": "2",
"serialNumber": "0",
"status": "Free",
"isBlocked": "N",
"voucherPin": "0",
"buyDate": null,
"redeemDate": null,
"phoneNumber": null,
"statusCode": null,
"identifier": "MCM0007532",
"merchantName": "test1",
"voucherName": "fddf",
"expiryDate": "2016-02-24 00:00:00",
"dealCategory": "Hotels \u0026 Travel",
"shortDescription": "xvxv",
"voucherWorth": "33.00"
}]
}],
"message": null}
I used it as,
vm.dtOptions = DTOptionsBuilder
.newOptions()
.withOption('ajax', {
url: config.base_url + 'report/voucher?module=Vouchers&type=Total Voucher Report&merchant=1',
type: 'POST',
dataSrc: 'data.data[0].reportData[0]',
})
.withOption('processing', true)
.withOption('serverSide', true)
.withBootstrap()
.withPaginationType('full_numbers');
It says invalid JSON response. Appreciate your kindly help.
Debug result: http://debug.datatables.net/urizon

Use the following value for dataSrc option: data[0].reportData as shown below. Also you need to remove serverSide and processing options since your data doesn't have correct structure for server-side processing mode.
You also need to define columns structure since you're using array of objects as your data source.
vm.dtOptions = DTOptionsBuilder
.newOptions()
.withOption('ajax', {
url: config.base_url + 'report/voucher?module=Vouchers&type=Total Voucher Report&merchant=1',
type: 'POST',
dataSrc: 'data[0].reportData'
})
.withBootstrap()
.withPaginationType('full_numbers');
vm.dtColumns = [
/* List data properties for each column in the table. */
DTColumnBuilder.newColumn('id'),
DTColumnBuilder.newColumn('voucherPackId'),
DTColumnBuilder.newColumn('serialNumber'),
DTColumnBuilder.newColumn('status')
];

If your use a parser your will get error : SyntaxError: JSON.parse: end of data after property value in object at line 63 column 16 of the JSON data. So yes your JSON is invalid ! Just add } on list line. Because every brackets need to be closed.

Make sure the JSON response has Content-Type: application/json header, otherwise it might not be parsed correctly.

Related

Getting values from JSON multidimensional array?

I have a JSON array that looks like this:
{
"id": 258,
"rawId": null,
"displayName": null,
"name": {
"givenName": "my ame",
"honorificSuffix": "",
"formatted": "my ame",
"middleName": "",
"familyName": "",
"honorificPrefix": ""
},
"nickname": "",
"phoneNumbers": [{
"value": "23423442342424",
"pref": false,
"id": 0,
"type": "mobile"
}],
"emails": null,
"addresses": null,
"ims": null,
"organizations": [{
"pref": "false",
"title": "",
"name": "",
"department": "",
"type": null
}],
"birthday": null,
"note": "",
"photos": null,
"categories": null,
"urls": null
}
I need to get the phoneNumbers >> value from this JSON.
SO I TRIED SOMETHING LIKE THIS:
var d = JSON.parse(test);
alert(test[0].phoneNumbers.value);
The variable test is the JSON shown above.
and I also tried:
alert(d[0].phoneNumbers.value);
and
alert(test.phoneNumbers.value);
But none of the above work.
Is there something that I am missing in my code?
Thanks in advance.
What you showed us is a JSON string (giving a JS object after parsing), not an array.
So d[0].phoneNumbers will not work and d.phoneNumbers will work and will give you an array.
And because it will give you an array, d.phoneNumbers.value will not work, and d.phoneNumbers[0].value will.

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.

How to insert values of matching JSON Keys between 2 JSON files

I have 2 JSON files:
A Template JSON
A JSON output (from awscli)
The template is a small JSON file as below:
{
"DryRun": true,
"ImageId": "",
"KeyName": "",
"SecurityGroups": [
""
],
"InstanceType": "",
"Monitoring": {
"Enabled": false
},
"SubnetId": "",
"DisableApiTermination": true,
"PrivateIpAddress": "",
"IamInstanceProfile": {
"Arn": "",
"Name": ""
},
"EbsOptimized": true,
"TagSpecifications": [{
"ResourceType": "",
"Tags": [{
"Key": "",
"Value": ""
}]
}]
}
The original file is the output of aws ec2 describe-instances:
{
"Reservations": [{
"OwnerId": "123456789012",
"ReservationId": "r-12345678",
"Groups": [],
"Instances": [{
"Monitoring": {
"State": "disabled"
},
"PublicDnsName": "ec2-12-34-56-78.ap-southeast-1.compute.amazonaws.com",
"RootDeviceType": "ebs",
"State": {
"Code": 16,
"Name": "running"
},
"EbsOptimized": false,
"LaunchTime": "2016-02-09T03:06:21.000Z",
"PublicIpAddress": "12.34.56.78",
"PrivateIpAddress": "172.31.1.2",
"ProductCodes": [],
"VpcId": "vpc-1a2b3c4d",
"StateTransitionReason": "",
"InstanceId": "i-abcd1234",
"ImageId": "ami-1234abcd",
"PrivateDnsName": "ip-172-31-1-2.ap-southeast-1.compute.internal",
"KeyName": "tempKey",
"SecurityGroups": [{
"GroupName": "somegroup1",
"GroupId": "sg-ZZZZZ"
},
{
"GroupName": "somegroup2",
"GroupId": "sg-YYYYY"
}
],
"ClientToken": "NutKc123456789012",
"SubnetId": "subnet-00001234",
"InstanceType": "t2.medium",
"NetworkInterfaces": [{
"Status": "in-use",
"MacAddress": "02:AA:BB:CC:DD:EE",
"SourceDestCheck": true,
"VpcId": "vpc-1a2b3c4d",
"Description": "",
"Association": {
"PublicIp": "12.34.56.78",
"PublicDnsName": "ec2-12-34-56-78.ap-southeast-1.compute.amazonaws.com",
"IpOwnerId": "123456789012"
},
"NetworkInterfaceId": "eni-XXXXXXXX",
"PrivateIpAddresses": [{
"PrivateDnsName": "ip-172-31-1-2.ap-southeast-1.compute.internal",
"Association": {
"PublicIp": "1.2.3.4",
"PublicDnsName": "ec2-12-34-56-78.ap-southeast-1.compute.amazonaws.com",
"IpOwnerId": "123456789012"
},
"Primary": true,
"PrivateIpAddress": "172.31.1.2"
}],
"PrivateDnsName": "ip-172-31-1-2.ap-southeast-1.compute.internal",
"Attachment": {
"Status": "attached",
"DeviceIndex": 0,
"DeleteOnTermination": true,
"AttachmentId": "eni-attach-XXXXXXXX",
"AttachTime": "2016-01-13T08:33:37.000Z"
},
"Groups": [{
"GroupName": "somegroup1",
"GroupId": "sg-ZZZZZZ"
},
{
"GroupName": "somegroup2",
"GroupId": "sg-YYYYYY"
}
],
"Ipv6Addresses": [],
"SubnetId": "subnet-00001234",
"OwnerId": "123456789012",
"PrivateIpAddress": "172.31.1.2"
}],
"SourceDestCheck": true,
"Placement": {
"Tenancy": "default",
"GroupName": "",
"AvailabilityZone": "ap-southeast-1b"
},
"Hypervisor": "xen",
"BlockDeviceMappings": [{
"DeviceName": "/dev/xvda",
"Ebs": {
"Status": "attached",
"DeleteOnTermination": true,
"VolumeId": "vol-33221100",
"AttachTime": "2016-01-13T08:33:39.000Z"
}
}],
"Architecture": "x86_64",
"StateReason": {
"Message": "Client.UserInitiatedShutdown: User initiated shutdown",
"Code": "Client.UserInitiatedShutdown"
},
"RootDeviceName": "/dev/xvda",
"VirtualizationType": "hvm",
"Tags": [{
"Value": "SomeValue",
"Key": "SomeKey"
},
{
"Value": "AnotherValue",
"Key": "Name"
}
],
"AmiLaunchIndex": 0
}]
}]
}
I want to copy the values of the Keys in the original JSON file to the template file.
For example, KeyName is a common key between the 2 JSON files. The corresponding value tempKey is replaced in the template file.
The main use case of this is: I am trying to migrate a number of servers on AWS from 1 region to another. This is a part of migration process which will remove tons of manual clicking and configuration on AWS Console.
Note: I use BASH command line.
There's a way to do this with jq but it doesn't take a JSON template as input.
You'll have to modify it to become a query. This isn't the actual query you need, but something to get you started:
cat temp.json | jq '.Reservations[].Instances[] | { DryRun, ImageId, KeyName, SecurityGroups, InstanceType, Monitoring }'
Where temp.json is your output above that I placed into a file. For regular commands, just do something like aws ec2 describe-instances | jq ...
The output that gives me (keep in mind the restricted set I queried for) is:
{
"DryRun": null,
"ImageId": "ami-1234abcd",
"KeyName": "tempKey",
"SecurityGroups": [
{
"GroupName": "somegroup1",
"GroupId": "sg-ZZZZZ"
},
{
"GroupName": "somegroup2",
"GroupId": "sg-YYYYY"
}
],
"InstanceType": "t2.medium",
"Monitoring": {
"State": "disabled"
}
}
Hope this helps.

Can't get value of Object in Javascript , nodejs, stripe library

Im trying to get a value "status" from "customer" object with this simple script:
console.log(JSON.stringify(customer.subscriptions.data.plan.status));
When i execute this function, the console returns me:
TypeError: Cannot read property 'data' of undefined
"customer" Object:
customer: {
"object":"customer",
"created":xxxxxx,
"id":"xxxxxxx",
"livemode":false,
"description":null,
"email":"xxxx#xxxx.com",
"shipping":null,
"delinquent":false,
"metadata":{},
"subscriptions":{
"object":"list",
"total_count":1,
"has_more":false,
"url":"/v1/customers/xxxxxxxxx/subscriptions",
"data":[{
"id":"xxxxxxxxx",
"plan":{
"interval":"month",
"name":"xxxxxx",
"created":xxxxx,
"amount":xxxxx,
"currency":"eur",
"id":"6month",
"object":"plan",
"livemode":false,
"interval_count":6,
"trial_period_days":null,
"metadata":{},
"statement_descriptor":null,
"statement_description":null},
"object":"subscription",
"start":xxxxx,
"status":"active",
...,
Please help me.
Thanks.
The error doesn't match up with the data. It should be that it can't read status of undefined. This is because customer does have subscriptions, and subscriptions does have data, but then you're treating data as though it had a plan property, which it doesn't. data refers to an array, the first entry of which has a plan property. Also note that status is not a property of plan, it's a property of the same object that plan is a property of.
So accessing the first entry's status would be:
customer.subscriptions.data[0].status
// Note -------------------^^^
If there are subsequent entries in data, they would be at indexes 1, 2, 3, etc.
Example:
var customer = {
"object": "customer",
"created": "xxxxxx",
"id": "xxxxxxx",
"livemode": false,
"description": null,
"email": "xxxx#xxxx.com",
"shipping": null,
"delinquent": false,
"metadata": {},
"subscriptions": {
"object": "list",
"total_count": 1,
"has_more": false,
"url": "/v1/customers/xxxxxxxxx/subscriptions",
"data": [
{
"id": "xxxxxxxxx",
"plan": {
"interval": "month",
"name": "xxxxxx",
"created": "xxxxx",
"amount": "xxxxx",
"currency": "eur",
"id": "6month",
"object": "plan",
"livemode": false,
"interval_count": 6,
"trial_period_days": null,
"metadata": {},
"statement_descriptor": null,
"statement_description": null
},
"object": "subscription",
"start": "xxxxx",
"status": "active"
}
]
}
};
document.body.innerHTML = customer.subscriptions.data[0].status;

how to return null composite objects in mql

I have been working on a simple calorie counter using freebase. When I am querying for a recipe I am not getting all the entries returned.
My query is:
[{
"id": "/m/0e cvb9k7",
"name": null,
"/food/recipe/ingredients": [{
"id": null,
"ingredient": {
"id": null,
"name": null,
"/food/food/energy": null
},
"unit": {
"id": null,
"name": null
},
"quantity": null
}]
}]
For example, in the gumbo recipe there are ingredients like onions or peppers where unit is null. Those are not returned by this query. How do I write a query that will return all the ingredients, including the ones with null units?
I tried:
"unit|=": [
null,
{
"id": null,
"name": null
}
]
This gave me an error Comparison operator |= takes a non-empty list of values.
Add "optional": true to that subquery viz
[{
"id": "/m/0e cvb9k7",
"name": null,
"/food/recipe/ingredients": [{
"id": null,
"ingredient": {
"id": null,
"name": null,
"/food/food/energy": null
},
"unit": {
"id": null,
"name": null
"optional":true
},
"quantity": null
}]
}]

Categories

Resources