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

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;

Related

Trying to access object in Api array and count length

Trying to access the mythic object and print the length of mythic's that exist in the account but unsure how to access it as its nested in the array. Api output is below Javascript. Just not sure exactly what I can use to get its length as I used json.mythic.length and that did not work. And Thank you very much to anyone who is able to help me with this problem.
function MyFunction(e) {
e.preventDefault();
var username = document.getElementById("username").value
document.getElementById("search").innerHTML = username;
const data = {
username, limit: 3000, offset: 0, rarities: [], markers: [], onSale: "", search: "" }
fetch("https://prod-eternal-backend.onrender.com/api/v1/moment/list" ,{
method: "POST",
body: JSON.stringify(data),
headers: {
"Content-type": "application/json; charset=UTF-8"
}
})
.then(response => {
return response.json();
})
.then(json => {
console.log(json);
document.getElementById("moments").innerHTML ="Total Moments = " + json.moments.length;
var mythics = json.mythic.length * 50;
document.getElementById("gamer").innerHTML ="Gamer Score = " + mythics;
})
}
{
"moments": [
{
"id": 114375,
"playId": 536,
"setId": 16,
"serialNumber": 4,
"username": "pattonh84",
"userId": 1230,
"userAuthId": "AqXfuefDt5a5wfqAoIa45O1RKbd2",
"influencer": "YuggieTV",
"influencerId": "YuggieTV",
"influencerAvatar": "https://eternal-zelos.s3.us-west-2.amazonaws.com/influencers/YuggieTV_square.png",
"playbackId": "QXMRHp9R4uFcSsCQkN7mBCDbSmFZdImdjeUHypEutRw",
"rarity": "mythic",
"createdAt": "2021-10-25T00:11:54.734962Z",
"setName": "Flow State",
"circulationCount": 30,
"title": "How Strong Could It Be?",
"imageURL": "https://eternal-zelos.s3.us-west-2.amazonaws.com/images/FlowFest/Let+Me+See+How+Strong+It+Is.png",
"packName": "Flow State",
"clipDate": "2021-09-26T02:55:28Z",
"tags": [
"funny"
],
"description": "Yuggie doing experiments in the name of science. Today's experiment is about how strong a watermelon could be.",
"game": "IRL",
"twitter": "yuggietv",
"staked": false,
"autographStatus": "false",
"discordUtility": false,
"markers": null
},
{
"id": 108262,
"playId": 565,
"setId": 16,
"serialNumber": 1,
"username": "pattonh84",
"userId": 1230,
"userAuthId": "AqXfuefDt5a5wfqAoIa45O1RKbd2",
"influencer": "Amouranth",
"influencerId": "Amouranth",
"influencerAvatar": "https://eternal-zelos.s3.us-west-2.amazonaws.com/influencers/Amouranth.jpg",
"playbackId": "101L8XUOTCKkJW3USj6rtiJm5k4iTAwTIMqcxfPsr8QA",
"rarity": "mythic",
"createdAt": "2021-10-22T17:07:38.357172Z",
"setName": "Flow State",
"circulationCount": 30,
"title": "Mare Awareness",
"imageURL": "https://eternal-zelos.s3.us-west-2.amazonaws.com/images/FlowFest/amouranth+pretending+to+be+a+horse.png",
"packName": "Flow State",
"clipDate": "2021-09-26T04:21:46Z",
"tags": [
"funny"
],
"description": "Now a popular gif, this clip showcases a horse performance complete with galloping and internal monalogue.",
"game": "Just Chatting",
"twitter": "Amouranth",
"staked": false,
"autographStatus": "pending",
"autographRequestId": 2071,
"discordUtility": false,
"markers": null
},
{
"id": 114393,
"playId": 536,
"setId": 16,
"serialNumber": 22,
"username": "pattonh84",
"userId": 1230,
"userAuthId": "AqXfuefDt5a5wfqAoIa45O1RKbd2",
"influencer": "YuggieTV",
"influencerId": "YuggieTV",
"influencerAvatar": "https://eternal-zelos.s3.us-west-2.amazonaws.com/influencers/YuggieTV_square.png",
"playbackId": "QXMRHp9R4uFcSsCQkN7mBCDbSmFZdImdjeUHypEutRw",
"rarity": "mythic",
"createdAt": "2021-10-22T03:35:24.934307Z",
"setName": "Flow State",
"forSale": true,
"circulationCount": 30,
"price": 200,
"title": "How Strong Could It Be?",
"imageURL": "https://eternal-zelos.s3.us-west-2.amazonaws.com/images/FlowFest/Let+Me+See+How+Strong+It+Is.png",
"packName": "Flow State",
"clipDate": "2021-09-26T02:55:28Z",
"tags": [
"funny"
],
"description": "Yuggie doing experiments in the name of science. Today's experiment is about how strong a watermelon could be.",
"game": "IRL",
"twitter": "yuggietv",
"staked": false,
"autographStatus": "false",
"discordUtility": false,
"productId": 67358,
"markers": null
}
],
"totalMoments": 3
}
You are trying to access a mythic property on your JSON object, but your data does not have such a property. I would recommend that you study more on JSON structure and accessing properties in javascript.
Basically, json.mythics checks for a property called mythics in the root level of your json object, the same way json.moments does. If your data was organized like:
{
"moments": [...],
"mythics": [...]
}
then you would access it with json.mythics
But your json only has a moments array of objects, some of which have a rarity property set to "mythic".
Assuming you want to filter out these elements from the array, a simple filter should suffice:
const mythics = json.moments.filter(moment => moment.rarity === 'mythic');
mythics.length // gives the length of the 'mythics'

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.

trouble while parsing json

I am trying to react displayName in req
when I write
console.log(req.session.passport.user._raw)
the output is:
{
"kind": "plus#person",
"etag": "\"ucaTEV-ZanNH5M3SCxYRM0QRw2Y/XiR7kPThRbzcIw-YLiARoF22TMY\"",
"emails": [
{
"value": "rajanlagah#gmail.com",
"type": "account"
}
],
"objectType": "person",
"id": "100428644453494579140",
"displayName": "Rajan Lagah",
"name": {
"familyName": "Lagah",
"givenName": "Rajan"
},
"url": "https://plus.google.com/100428644453494579140",
"image": {
"url": "https://lh3.googleusercontent.com/-XdUIqdMkCWA/AAAAAAAAAAI/AAAAAAAAAAA/4252rscbv5M/photo.jpg?sz=50",
"isDefault": true
},
"isPlusUser": true,
"language": "en",
"circledByCount": 0,
"verified": false
}
Now the from this object I am trying to get kind (say)
console.log(req.session.passport.user._raw.kind)
then the output is undefined
Can any one tell my mistake?
Is req.session.passport.user._raw a string? You may need to parse it first, eg:
var data = JSON.parse(req.session.passport.user._raw);
console.log(data.kind);

How to use this json with angular datatables

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.

Mandrill handlebars example

The variables in my html content appear to be stripped so no dynamic content is showing up in the email. The template language is set to handlebars in the code and globally.
The documentation does not appear to give any other details or examples. There are no error messages.
var subject = "A really great subject";
var htmlContent = "<h1>Hi, {{user}}</h1><p>{{productName}}?</p><br/><a href='{{unsub redirect_merge_var}}'>Unsubscribe</a>"
var mailJSON ={
"key": "myKey",
"merge_language": "handlebars",
"merge": true,
"global_merge_vars": [
{
"name": "productName",
"content": "Mandrill_User1"
},
{
"name": "user",
"content": "cool guy"
}
],
"message": {
"html": htmlContent,
"subject": subject,
"from_email": "stuff#xxxxxxxxxx.com",
"from_name": "stuff-app",
"to": [
{
"email": ""+person.email,
"name": ""+person.name,
"type": "to"
}
],
"important": false,
"track_opens": null,
"track_clicks": null,
"auto_text": null,
"auto_html": null,
"inline_css": null,
"url_strip_qs": null,
"preserve_recipients": null,
"view_content_link": null,
"tracking_domain": null,
"signing_domain": null,
"return_path_domain": null
},
"async": false,
"ip_pool": "Main Pool"
}
move this:
"merge_language": "handlebars",
"merge": true,
"global_merge_vars": […],
into your message struct. (Official API documentation)
You can also remove your NULL values if you don't need them.

Categories

Resources