Stripe invoice.upcoming webhook - javascript

I want to know what is the example data from invoice.upcoming webhook of stripe.
Is the data.object.id is null?
Where I can get the amount? Is it on the data.object.amount_paid or data.object.amount_due?
And what is the status of this invoice?
Example data I got here in stackoverflow but I think it's not complete?
{
"created": 1326853478,
"livemode": false,
"id": "evt_000000000010000",
"type": "invoice.upcoming",
"object": "event",
"request": null,
"pending_webhooks": 1,
"api_version": "2017-06-05",
"data": {
"object": {
"id": null,
"object": "invoice",
"amount_due": 0,
"amount_paid": 0,
"application_fee": null,
"attempt_count": 0,
"attempted": true,
"charge": null,
"closed": true,
"currency": "usd",
"customer": "cus_J1QXR23OrUTxx1fk",
"date": 1503541536,
"description": null,
"discount": null,
"ending_balance": 0,
"forgiven": false,
"lines": {
"data": [
{
"id": "sub_BNx15yNiTkAlQOye",
"object": "line_item",
"amount": 500,
"currency": "jpy",
"description": null,
"discountable": true,
"livemode": true,
"metadata": {
},
"period": {
"start": 1507604796,
"end": 1510283196
},
"plan": {
"id": "bplan",
"object": "plan",
"amount": 500,
"created": 1504352393,
"currency": "jpy",
"interval": "month",
"interval_count": 1,
"livemode": false,
"metadata": {
},
"name": "B plan",
"statement_descriptor": null,
"trial_period_days": null
},
"proration": false,
"quantity": 1,
"subscription": null,
"subscription_item": "si_1B0LmKE9P3qCpf5erqbpMxkI",
"type": "subscription"
}
],
"total_count": 1,
"object": "list",
"url": "/v1/invoices/in_1AuB2KE9P3qCpf5ekFh7qpAi/lines"
},
"livemode": false,
"metadata": {
},
"next_payment_attempt": null,
"paid": true,
"period_end": 1503541536,
"period_start": 1503541536,
"receipt_number": null,
"starting_balance": 0,
"statement_descriptor": null,
"subscription": "sub2JQx1xlg9zIFhk",
"subtotal": 0,
"tax": null,
"tax_percent": null,
"total": 0,
"webhooks_delivered_at": 1503541537
}
}
}

Those Events generated from the Dashboard are totally fake, so I don't think you'll ever find usable data in them, but amount_due is what you want here.
Since Upcoming Invoices haven't been created yet - they're just a preview of future charges - they have no ID or status.

Here's a full example of Stripe's invoice.upcoming event.
I found it using the test clocks feature. Please note that is the kind of data you'll get by renewing a yearly susbscription.
{
"object": "invoice",
"account_country": "US",
"account_name": "Your company",
"account_tax_ids": null,
"amount_due": 9900,
"amount_paid": 0,
"amount_remaining": 9900,
"application_fee_amount": null,
"attempt_count": 0,
"attempted": false,
"automatic_tax": {
"enabled": false,
"status": null
},
"billing_reason": "upcoming",
"charge": null,
"collection_method": "charge_automatically",
"created": 1679397051,
"currency": "usd",
"custom_fields": null,
"customer": "cus_XXXXXXXX",
"customer_address": null,
"customer_email": "xxxx#user.io",
"customer_name": "Customer name",
"customer_phone": null,
"customer_shipping": null,
"customer_tax_exempt": "none",
"customer_tax_ids": [],
"default_payment_method": null,
"default_source": null,
"default_tax_rates": [],
"description": null,
"discount": null,
"discounts": [],
"due_date": null,
"ending_balance": 0,
"footer": null,
"last_finalization_error": null,
"lines": {
"object": "list",
"data": [
{
"id": "il_tmp_xxxxxxxxxxxxxxxxxxxxxxx",
"object": "line_item",
"amount": 9900,
"currency": "usd",
"description": "1 × Your sub (at $99.00 / year)",
"discount_amounts": [],
"discountable": true,
"discounts": [],
"livemode": false,
"metadata": {},
"period": {
"end": 1711019451,
"start": 1679397051
},
"plan": {
"id": "price_XXXXXXXXXXXXXXXX",
"object": "plan",
"active": true,
"aggregate_usage": null,
"amount": 9900,
"amount_decimal": "9900",
"billing_scheme": "per_unit",
"created": 1600678675,
"currency": "usd",
"interval": "year",
"interval_count": 1,
"livemode": false,
"metadata": {},
"nickname": null,
"product": "prod_XXXXXXXXXXXX",
"tiers_mode": null,
"transform_usage": null,
"trial_period_days": null,
"usage_type": "licensed"
},
"price": {
"id": "price_XXXXXXXXXXXXXX",
"object": "price",
"active": true,
"billing_scheme": "per_unit",
"created": 1600678675,
"currency": "usd",
"livemode": false,
"lookup_key": null,
"metadata": {},
"nickname": null,
"product": "prod_XXXXXXXXXXXX",
"recurring": {
"aggregate_usage": null,
"interval": "year",
"interval_count": 1,
"trial_period_days": null,
"usage_type": "licensed"
},
"tax_behavior": "unspecified",
"tiers_mode": null,
"transform_quantity": null,
"type": "recurring",
"unit_amount": 9900,
"unit_amount_decimal": "9900"
},
"proration": false,
"proration_details": {
"credited_items": null
},
"quantity": 1,
"subscription": "sub_XXXXXXXXXXXXXX",
"subscription_item": "si_XXXXXXXXXXXX",
"tax_amounts": [],
"tax_rates": [],
"type": "subscription"
}
],
"has_more": false,
"total_count": 1,
"url": "/v1/invoices/upcoming/lines?customer=cus_XXXXXXXXXXXX&subscription=sub_XXXXXXXXXXX"
},
"livemode": false,
"metadata": {},
"next_payment_attempt": 1679400651,
"number": null,
"on_behalf_of": null,
"paid": false,
"paid_out_of_band": false,
"payment_intent": null,
"payment_settings": {
"payment_method_options": null,
"payment_method_types": null
},
"period_end": 1679397051,
"period_start": 1647861051,
"post_payment_credit_notes_amount": 0,
"pre_payment_credit_notes_amount": 0,
"quote": null,
"receipt_number": null,
"starting_balance": 0,
"statement_descriptor": null,
"status": "draft",
"status_transitions": {
"finalized_at": null,
"marked_uncollectible_at": null,
"paid_at": null,
"voided_at": null
},
"subscription": "sub_XXXXXXXXXXXX",
"subtotal": 9900,
"tax": null,
"test_clock": "clock_1Kfj8pAP8XE2C2mat1YQW7Rg",
"total": 9900,
"total_discount_amounts": [],
"total_tax_amounts": [],
"transfer_data": null,
"webhooks_delivered_at": null
}

Related

Incorrect Maquest Direction Route API Feedback

I am integrating the MapQuest API Direction Routing function into my website. However, when I submit my request to the API, it returns incorrect routing points between 2 destinations.
Below is the request form I POST to the API: http://www.mapquestapi.com/directions/v2/route?key=[APIKEY]
{
"locations": [
{
"latLng": {
"lat": 37.47601247,
"lng": 126.96594338
}
},
{
"latLng": {
"lat": 37.4713402954355,
"lng": 126.95234849232048
}
}
],
"options": {
"avoids": [],
"avoidTimedConditions": false,
"doReverseGeocode": false,
"enhancedNarrative": true,
"generalize": 0,
"narrativeType": "text",
"routeType": "fastest",
"shapeFormat": "raw",
"unit": "k"
}
}
And the results that I received, I used the startPoint.lng and startPoint.lat in the maneuvers, but that doesn't seem to be correct
Below is the return results and map illustrations:
{
"route": {
"sessionId": "AHEA5gcAAFMBAAANAAAAMgAAAIQAAAB42mNoYWBgZGJgYGDPSC1KtUrOfcOaA-IybLykdYbrcqHnrSM-y6L8v3nd4t63PIoBC0DXeI7hyGImxx9ut9iLl0YdZPO69S5mBVaNILAwZvIzEA0AW5Egkyj61e4:car",
"realTime": 31,
"distance": 0.6,
"time": 31,
"formattedTime": "00:00:31",
"hasHighway": false,
"hasTollRoad": false,
"hasBridge": false,
"hasSeasonalClosure": false,
"hasTunnel": false,
"hasFerry": false,
"hasUnpaved": false,
"hasTimedRestriction": false,
"hasCountryCross": false,
"shape": {
"shapePoints": [
37.483936,
126.974279,
37.48681,
126.96995,
37.487346,
126.969139
],
"legIndexes": [
0,
3
],
"maneuverIndexes": [
0,
2
]
},
"legs": [
{
"index": 0,
"hasTollRoad": false,
"hasHighway": false,
"hasBridge": false,
"hasUnpaved": false,
"hasTunnel": false,
"hasSeasonalClosure": false,
"hasFerry": false,
"hasCountryCross": false,
"hasTimedRestriction": false,
"distance": 0.6,
"time": 31,
"formattedTime": "00:00:31",
"origIndex": 0,
"origNarrative": "",
"destIndex": 0,
"destNarrative": "",
"maneuvers": [
{
"index": 0,
"distance": 0.6,
"narrative": "Head northwest. Go for 591 m.",
"time": 31,
"direction": 2,
"directionName": "Northwest",
"signs": [],
"maneuverNotes": [],
"formattedTime": "00:00:31",
"transportMode": "car",
"startPoint": {
"lng": 126.974279,
"lat": 37.483936
},
"turnType": 0,
"mapUrl": "",
"attributes": 0,
"iconUrl": "",
"streets": []
},
{
"index": 1,
"distance": 0,
"narrative": "Arrive at your destination.",
"time": 0,
"direction": 0,
"directionName": "None",
"signs": [],
"maneuverNotes": [],
"formattedTime": "00:00:00",
"transportMode": "car",
"startPoint": {
"lng": 126.969139,
"lat": 37.487345999999995
},
"turnType": 0,
"mapUrl": "",
"attributes": 0,
"iconUrl": "",
"streets": []
}
]
}
],
"options": {
"avoids": [],
"avoidTimedConditions": false,
"doReverseGeocode": false,
"enhancedNarrative": true,
"generalize": 2,
"narrativeType": "text",
"routeType": "FASTEST",
"shapeFormat": "raw",
"unit": "K",
"walkingSpeed": -1,
"highwayEfficiency": 22,
"locale": "en_US",
"useTraffic": false,
"timeType": 0,
"dateType": 0,
"sideOfStreetDisplay": true
},
"boundingBox": {
"ul": {
"lng": 126.969139,
"lat": 37.487345999999995
},
"lr": {
"lng": 126.974279,
"lat": 37.483936
}
},
"routeWarnings": [],
"maxRoutes": "",
"locations": [
{
"street": "",
"adminArea6": "",
"adminArea6Type": "Neighborhood",
"adminArea5": "",
"adminArea5Type": "City",
"adminArea4": "",
"adminArea4Type": "County",
"adminArea3": "",
"adminArea3Type": "State",
"adminArea1": "",
"adminArea1Type": "Country",
"postalCode": "",
"geocodeQualityCode": "XXXXX",
"geocodeQuality": "LATLNG",
"dragPoint": false,
"sideOfStreet": "N",
"linkId": "0",
"unknownInput": "",
"type": "s",
"latLng": {
"lat": 37.47601247,
"lng": 126.96594338
},
"displayLatLng": {
"lat": 37.47601247,
"lng": 126.96594338
}
},
{
"street": "",
"adminArea6": "",
"adminArea6Type": "Neighborhood",
"adminArea5": "",
"adminArea5Type": "City",
"adminArea4": "",
"adminArea4Type": "County",
"adminArea3": "",
"adminArea3Type": "State",
"adminArea1": "",
"adminArea1Type": "Country",
"postalCode": "",
"geocodeQualityCode": "XXXXX",
"geocodeQuality": "LATLNG",
"dragPoint": false,
"sideOfStreet": "N",
"linkId": "0",
"unknownInput": "",
"type": "s",
"latLng": {
"lat": 37.4713402954355,
"lng": 126.95234849232048
},
"displayLatLng": {
"lat": 37.4713402954355,
"lng": 126.95234849232048
}
}
],
"locationSequence": [
0,
1
]
},
"info": {
"statuscode": 0,
"copyright": {
"text": "© 2022 MapQuest, Inc.",
"imageUrl": "http://api.mqcdn.com/res/mqlogo.gif",
"imageAltText": "© 2022 MapQuest, Inc."
},
"messages": []
}
}
Are there any parameters I have to adjust to archive the correct information? I have tried to change generalize parameter but it does not help much. I used to get the location really precise about a month ago... This is strange to me
MapQuest's map/route data in South Korea is lacking a lot of detail. We hope some day to have more detailed routing in the area.

Remove extra layer from object

I have some web-hook which returns next data:
"data": {
"object": {
"id": "cus_JYmRConwwwbDjw",
"object": "customer",
"address": null,
"balance": 0,
"created": 1622105261,
"currency": null,
"default_source": null,
"delinquent": false,
"description": null,
"discount": null,
"email": null,
"invoice_prefix": "7BA9446D",
"invoice_settings": {
"custom_fields": null,
"default_payment_method": "pm_1Ivesgeee6awlUaOWjDDzmv",
"footer": null
},
"livemode": false,
"metadata": {},
"name": null,
"next_invoice_sequence": 1,
"phone": null,
"preferred_locales": [],
"shipping": null,
"sources": {
"object": "list",
"data": [],
"has_more": false,
"total_count": 0,
"url": "/v1/customers/cus_JYmRCewwea5bDjw/sources"
},
"subscriptions": {
"object": "list",
"data": [],
"has_more": false,
"total_count": 0,
"url": "/v1/customers/cus_JYmewenGa5bDjw/subscriptions"
},
"tax_exempt": "none",
"tax_ids": {
"object": "list",
"data": [],
"has_more": false,
"total_count": 0,
"url": "/v1/customers/cus_JYmRCowea5bDjw/tax_ids"
},
"tax_info": null,
"tax_info_verification": null
},
"previous_attributes": {
"invoice_settings": {
"default_payment_method": null
}
}
},
"type": "customer.updated"
}
To access for example id I need to use next path data.object.id.
How I can avoid using this not readable, not needed object item in path?
What I need is data.id

I want to flat a nested arrays of objects and convert them into one object array

I have below type of JSON response coming from backend. I am displaying this response in grid table. For that I need only array of "projects" objects throughout the whole response. I am not able to get all projects together.
[{
"responseText": "Success",
"userName": "ranjeet.sh14#gmail.com",
"userId": 2,
"projectDetails": [{
"accountName": "ViewEnvironment",
"projects": [{
"responseText": "success",
"id": 34,
"projectName": "Plato",
"accountName": "ViewEnvironment",
"projectHealth": null,
"modulesCount": 0,
"cordinatorEmail": null,
"businessType": null,
"projectType": null,
"status": null,
"createdDate": null,
"createdBy": null,
"modifiedDate": null,
"modifiedBy": null,
"role": "DL/PM",
"roleId": 3,
"projectUserId": 89
}]
},
{
"accountName": "Accloud",
"projects": [{
"responseText": "success",
"id": 4,
"projectName": "Citi Test2",
"accountName": "Accloud",
"projectHealth": null,
"modulesCount": 0,
"cordinatorEmail": null,
"businessType": null,
"projectType": null,
"status": null,
"createdDate": null,
"createdBy": null,
"modifiedDate": null,
"modifiedBy": null,
"role": "Executive",
"roleId": 2,
"projectUserId": 83
},
{
"responseText": null,
"id": 5,
"projectName": "Citi Test3",
"accountName": "Accloud",
"projectHealth": null,
"modulesCount": 0,
"cordinatorEmail": null,
"businessType": null,
"projectType": null,
"status": null,
"createdDate": null,
"createdBy": null,
"modifiedDate": null,
"modifiedBy": null,
"role": "Executive",
"roleId": 2,
"projectUserId": 221
},
{
"responseText": null,
"id": 9,
"projectName": "Test_Project",
"accountName": "Accloud",
"projectHealth": null,
"modulesCount": 0,
"cordinatorEmail": null,
"businessType": null,
"projectType": null,
"status": null,
"createdDate": null,
"createdBy": null,
"modifiedDate": null,
"modifiedBy": null,
"role": "Executive",
"roleId": 2,
"projectUserId": 220
}
]
},
{
"accountName": "iBASE",
"projects": [{
"responseText": "success",
"id": 1,
"projectName": "iBase-Project-edit",
"accountName": "iBASE",
"projectHealth": null,
"modulesCount": 0,
"cordinatorEmail": null,
"businessType": null,
"projectType": null,
"status": null,
"createdDate": null,
"createdBy": null,
"modifiedDate": null,
"modifiedBy": null,
"role": "Admin",
"roleId": 1,
"projectUserId": 70
},
{
"responseText": null,
"id": 1,
"projectName": "iBase-Project-edit",
"accountName": "iBASE",
"projectHealth": null,
"modulesCount": 0,
"cordinatorEmail": null,
"businessType": null,
"projectType": null,
"status": null,
"createdDate": null,
"createdBy": null,
"modifiedDate": null,
"modifiedBy": null,
"role": "Admin",
"roleId": 1,
"projectUserId": 72
},
{
"responseText": null,
"id": 1,
"projectName": "iBase-Project-edit",
"accountName": "iBASE",
"projectHealth": null,
"modulesCount": 0,
"cordinatorEmail": null,
"businessType": null,
"projectType": null,
"status": null,
"createdDate": null,
"createdBy": null,
"modifiedDate": null,
"modifiedBy": null,
"role": "Admin",
"roleId": 1,
"projectUserId": 73
},
{
"responseText": null,
"id": 1,
"projectName": "iBase-Project-edit",
"accountName": "iBASE",
"projectHealth": null,
"modulesCount": 0,
"cordinatorEmail": null,
"businessType": null,
"projectType": null,
"status": null,
"createdDate": null,
"createdBy": null,
"modifiedDate": null,
"modifiedBy": null,
"role": "Developer",
"roleId": 5,
"projectUserId": 74
}
]
}
]
}]
I tried to do this with nested for loop but with that only last array is coming not all arrays . Like below.
for (let user of this.selectedUser) {
this.projectList = user.projectDetails;
for (project of this.projectList) {
(this.projectList2) = project.projects;
for (let proj of this.projectList2) {
this.finalProjectsList = proj;
}
}
}
console.log("projcetlist", this.projectList.projects)
Can anybody suggest better approach to get right response.
If you're using a browser that doesn't support Array.flatMap, you can achieve the result you want using a nested Array.reduce:
const projectList = selectedUser.reduce((p, { projectDetails }) =>
p.concat(projectDetails.reduce((c, { projects }) =>
c.concat(projects), [])
),
[]);
const selectedUser = [{
"responseText": "Success",
"userName": "ranjeet.sh14#gmail.com",
"userId": 2,
"projectDetails": [{
"accountName": "ViewEnvironment",
"projects": [{
"responseText": "success",
"id": 34,
"projectName": "Plato",
"accountName": "ViewEnvironment",
"projectHealth": null,
"modulesCount": 0,
"cordinatorEmail": null,
"businessType": null,
"projectType": null,
"status": null,
"createdDate": null,
"createdBy": null,
"modifiedDate": null,
"modifiedBy": null,
"role": "DL/PM",
"roleId": 3,
"projectUserId": 89
}]
},
{
"accountName": "Accloud",
"projects": [{
"responseText": "success",
"id": 4,
"projectName": "Citi Test2",
"accountName": "Accloud",
"projectHealth": null,
"modulesCount": 0,
"cordinatorEmail": null,
"businessType": null,
"projectType": null,
"status": null,
"createdDate": null,
"createdBy": null,
"modifiedDate": null,
"modifiedBy": null,
"role": "Executive",
"roleId": 2,
"projectUserId": 83
},
{
"responseText": null,
"id": 5,
"projectName": "Citi Test3",
"accountName": "Accloud",
"projectHealth": null,
"modulesCount": 0,
"cordinatorEmail": null,
"businessType": null,
"projectType": null,
"status": null,
"createdDate": null,
"createdBy": null,
"modifiedDate": null,
"modifiedBy": null,
"role": "Executive",
"roleId": 2,
"projectUserId": 221
},
{
"responseText": null,
"id": 9,
"projectName": "Test_Project",
"accountName": "Accloud",
"projectHealth": null,
"modulesCount": 0,
"cordinatorEmail": null,
"businessType": null,
"projectType": null,
"status": null,
"createdDate": null,
"createdBy": null,
"modifiedDate": null,
"modifiedBy": null,
"role": "Executive",
"roleId": 2,
"projectUserId": 220
}
]
},
{
"accountName": "iBASE",
"projects": [{
"responseText": "success",
"id": 1,
"projectName": "iBase-Project-edit",
"accountName": "iBASE",
"projectHealth": null,
"modulesCount": 0,
"cordinatorEmail": null,
"businessType": null,
"projectType": null,
"status": null,
"createdDate": null,
"createdBy": null,
"modifiedDate": null,
"modifiedBy": null,
"role": "Admin",
"roleId": 1,
"projectUserId": 70
},
{
"responseText": null,
"id": 1,
"projectName": "iBase-Project-edit",
"accountName": "iBASE",
"projectHealth": null,
"modulesCount": 0,
"cordinatorEmail": null,
"businessType": null,
"projectType": null,
"status": null,
"createdDate": null,
"createdBy": null,
"modifiedDate": null,
"modifiedBy": null,
"role": "Admin",
"roleId": 1,
"projectUserId": 72
},
{
"responseText": null,
"id": 1,
"projectName": "iBase-Project-edit",
"accountName": "iBASE",
"projectHealth": null,
"modulesCount": 0,
"cordinatorEmail": null,
"businessType": null,
"projectType": null,
"status": null,
"createdDate": null,
"createdBy": null,
"modifiedDate": null,
"modifiedBy": null,
"role": "Admin",
"roleId": 1,
"projectUserId": 73
},
{
"responseText": null,
"id": 1,
"projectName": "iBase-Project-edit",
"accountName": "iBASE",
"projectHealth": null,
"modulesCount": 0,
"cordinatorEmail": null,
"businessType": null,
"projectType": null,
"status": null,
"createdDate": null,
"createdBy": null,
"modifiedDate": null,
"modifiedBy": null,
"role": "Developer",
"roleId": 5,
"projectUserId": 74
}
]
}
]
}];
const projectList = selectedUser.reduce((p, { projectDetails }) =>
p.concat(projectDetails.reduce((c, { projects }) =>
c.concat(projects), [])), []);
console.log(projectList)
You will need flatMap to flatten the array. Something like this you can implement:
const result = givenArray.flatMap(a=>a.projectDetails.flatMap(b=>b.projects));
Check browser compatibility table for flatMap before using this.

How to read multidimensional JSON array?

Let's say I have a JSON that looks like this:
[{
"created_at": "Sun Apr 09 17:56:20 +0000 2017",
"id": 851131679167139842,
"id_str": "851131679167139842",
"text": "hello world with an image goes here as a test! https:\/\/t.co\/jNfdESxPcn",
"truncated": false,
"entities": {
"hashtags": [],
"symbols": [],
"user_mentions": [],
"urls": [],
"media": [{
"id": 851131665623732225,
"id_str": "851131665623732225",
"indices": [47, 70],
"media_url": "http:\/\/pbs.twimg.com\/media\/C8_TvYqW0AEbBaP.jpg",
"media_url_https": "https:\/\/pbs.twimg.com\/media\/C8_TvYqW0AEbBaP.jpg",
"url": "https:\/\/t.co\/jNfdESxPcn",
"display_url": "pic.twitter.com\/jNfdESxPcn",
"expanded_url": "https:\/\/twitter.com\/DavidHoperz\/status\/851131679167139842\/photo\/1",
"type": "photo",
"sizes": {
"thumb": {
"w": 150,
"h": 150,
"resize": "crop"
},
"large": {
"w": 670,
"h": 728,
"resize": "fit"
},
"small": {
"w": 626,
"h": 680,
"resize": "fit"
},
"medium": {
"w": 670,
"h": 728,
"resize": "fit"
}
}
}]
},
"extended_entities": {
"media": [{
"id": 851131665623732225,
"id_str": "851131665623732225",
"indices": [47, 70],
"media_url": "http:\/\/pbs.twimg.com\/media\/C8_TvYqW0AEbBaP.jpg",
"media_url_https": "https:\/\/pbs.twimg.com\/media\/C8_TvYqW0AEbBaP.jpg",
"url": "https:\/\/t.co\/jNfdESxPcn",
"display_url": "pic.twitter.com\/jNfdESxPcn",
"expanded_url": "https:\/\/twitter.com\/DavidHoperz\/status\/851131679167139842\/photo\/1",
"type": "photo",
"sizes": {
"thumb": {
"w": 150,
"h": 150,
"resize": "crop"
},
"large": {
"w": 670,
"h": 728,
"resize": "fit"
},
"small": {
"w": 626,
"h": 680,
"resize": "fit"
},
"medium": {
"w": 670,
"h": 728,
"resize": "fit"
}
}
}]
},
"source": "\u003ca href=\"http:\/\/twitter.com\" rel=\"nofollow\"\u003eTwitter Web Client\u003c\/a\u003e",
"in_reply_to_status_id": null,
"in_reply_to_status_id_str": null,
"in_reply_to_user_id": null,
"in_reply_to_user_id_str": null,
"in_reply_to_screen_name": null,
"user": {
"id": 851119985732800513,
"id_str": "851119985732800513",
"name": "David",
"screen_name": "DavidHoperz",
"location": "",
"description": "",
"url": null,
"entities": {
"description": {
"urls": []
}
},
"protected": false,
"followers_count": 0,
"friends_count": 21,
"listed_count": 0,
"created_at": "Sun Apr 09 17:09:52 +0000 2017",
"favourites_count": 0,
"utc_offset": null,
"time_zone": null,
"geo_enabled": false,
"verified": false,
"statuses_count": 3,
"lang": "en",
"contributors_enabled": false,
"is_translator": false,
"is_translation_enabled": false,
"profile_background_color": "F5F8FA",
"profile_background_image_url": null,
"profile_background_image_url_https": null,
"profile_background_tile": false,
"profile_image_url": "http:\/\/pbs.twimg.com\/profile_images\/851182210732494848\/lmgbNLvC_normal.jpg",
"profile_image_url_https": "https:\/\/pbs.twimg.com\/profile_images\/851182210732494848\/lmgbNLvC_normal.jpg",
"profile_link_color": "1DA1F2",
"profile_sidebar_border_color": "C0DEED",
"profile_sidebar_fill_color": "DDEEF6",
"profile_text_color": "333333",
"profile_use_background_image": true,
"has_extended_profile": false,
"default_profile": true,
"default_profile_image": false,
"following": false,
"follow_request_sent": false,
"notifications": false,
"translator_type": "none"
},
"geo": null,
"coordinates": null,
"place": null,
"contributors": null,
"is_quote_status": false,
"retweet_count": 0,
"favorite_count": 0,
"favorited": false,
"retweeted": false,
"possibly_sensitive": false,
"lang": "en"
}, {
"created_at": "Sun Apr 09 17:47:36 +0000 2017",
"id": 851129482832470026,
"id_str": "851129482832470026",
"text": "How to display twitter posts using javascript https:\/\/t.co\/I49vjVbAUJ",
"truncated": false,
"entities": {
"hashtags": [],
"symbols": [],
"user_mentions": [],
"urls": [{
"url": "https:\/\/t.co\/I49vjVbAUJ",
"expanded_url": "https:\/\/www.script-tutorials.com\/how-to-display-twitter-posts-using-javascript\/",
"display_url": "script-tutorials.com\/how-to-display\u2026",
"indices": [46, 69]
}]
},
"source": "\u003ca href=\"http:\/\/twitter.com\" rel=\"nofollow\"\u003eTwitter Web Client\u003c\/a\u003e",
"in_reply_to_status_id": null,
"in_reply_to_status_id_str": null,
"in_reply_to_user_id": null,
"in_reply_to_user_id_str": null,
"in_reply_to_screen_name": null,
"user": {
"id": 851119985732800513,
"id_str": "851119985732800513",
"name": "David",
"screen_name": "DavidHoperz",
"location": "",
"description": "",
"url": null,
"entities": {
"description": {
"urls": []
}
},
"protected": false,
"followers_count": 0,
"friends_count": 21,
"listed_count": 0,
"created_at": "Sun Apr 09 17:09:52 +0000 2017",
"favourites_count": 0,
"utc_offset": null,
"time_zone": null,
"geo_enabled": false,
"verified": false,
"statuses_count": 3,
"lang": "en",
"contributors_enabled": false,
"is_translator": false,
"is_translation_enabled": false,
"profile_background_color": "F5F8FA",
"profile_background_image_url": null,
"profile_background_image_url_https": null,
"profile_background_tile": false,
"profile_image_url": "http:\/\/pbs.twimg.com\/profile_images\/851182210732494848\/lmgbNLvC_normal.jpg",
"profile_image_url_https": "https:\/\/pbs.twimg.com\/profile_images\/851182210732494848\/lmgbNLvC_normal.jpg",
"profile_link_color": "1DA1F2",
"profile_sidebar_border_color": "C0DEED",
"profile_sidebar_fill_color": "DDEEF6",
"profile_text_color": "333333",
"profile_use_background_image": true,
"has_extended_profile": false,
"default_profile": true,
"default_profile_image": false,
"following": false,
"follow_request_sent": false,
"notifications": false,
"translator_type": "none"
},
"geo": null,
"coordinates": null,
"place": null,
"contributors": null,
"is_quote_status": false,
"retweet_count": 2,
"favorite_count": 1,
"favorited": false,
"retweeted": false,
"possibly_sensitive": false,
"lang": "en"
}, {
"created_at": "Sun Apr 09 17:33:43 +0000 2017",
"id": 851125986976567297,
"id_str": "851125986976567297",
"text": "Hello world",
"truncated": false,
"entities": {
"hashtags": [],
"symbols": [],
"user_mentions": [],
"urls": []
},
"source": "\u003ca href=\"http:\/\/twitter.com\" rel=\"nofollow\"\u003eTwitter Web Client\u003c\/a\u003e",
"in_reply_to_status_id": null,
"in_reply_to_status_id_str": null,
"in_reply_to_user_id": null,
"in_reply_to_user_id_str": null,
"in_reply_to_screen_name": null,
"user": {
"id": 851119985732800513,
"id_str": "851119985732800513",
"name": "David",
"screen_name": "DavidHoperz",
"location": "",
"description": "",
"url": null,
"entities": {
"description": {
"urls": []
}
},
"protected": false,
"followers_count": 0,
"friends_count": 21,
"listed_count": 0,
"created_at": "Sun Apr 09 17:09:52 +0000 2017",
"favourites_count": 0,
"utc_offset": null,
"time_zone": null,
"geo_enabled": false,
"verified": false,
"statuses_count": 3,
"lang": "en",
"contributors_enabled": false,
"is_translator": false,
"is_translation_enabled": false,
"profile_background_color": "F5F8FA",
"profile_background_image_url": null,
"profile_background_image_url_https": null,
"profile_background_tile": false,
"profile_image_url": "http:\/\/pbs.twimg.com\/profile_images\/851182210732494848\/lmgbNLvC_normal.jpg",
"profile_image_url_https": "https:\/\/pbs.twimg.com\/profile_images\/851182210732494848\/lmgbNLvC_normal.jpg",
"profile_link_color": "1DA1F2",
"profile_sidebar_border_color": "C0DEED",
"profile_sidebar_fill_color": "DDEEF6",
"profile_text_color": "333333",
"profile_use_background_image": true,
"has_extended_profile": false,
"default_profile": true,
"default_profile_image": false,
"following": false,
"follow_request_sent": false,
"notifications": false,
"translator_type": "none"
},
"geo": null,
"coordinates": null,
"place": null,
"contributors": null,
"is_quote_status": false,
"retweet_count": 0,
"favorite_count": 0,
"favorited": false,
"retweeted": false,
"lang": "en"
}]
And I have a jQuery JSON that looks like this:
var poutput = $('.listHolder');
$.ajax({
url: 'page.php',
dataType: 'json',
timeout: 5000,
success: function(data){
$.each(data, function(pi,item){
str = item.id_str;
media = "";
var mediaUrl = item.entities.media.media_url_https;
alert(mediaUrl);
var products = '<div id="'+item.id_str+'" class="items">'+
'<p class="names">'+item.created_at+'</p>'+
'<p class="names">'+item.text+'</p>'+
media +
'</div>';
console.log(products);
poutput.append(products);
});
},
error: function(){
//alert('There was an error loading the data.');
}
});
I can easily get the created_at, text, and the id_str from that JSON but when I comes to getting the media_url or anything else, I always get an undefined error.
In my code above, I tried this:
var mediaUrl = item.entities.media.media_url_https;
alert(mediaUrl);
And it didn't work (undefined error).
I also tried:
var mediaUrl = item.entities.media_url_https;
alert(mediaUrl);
And still no luck.
Could someone please advise on this issue?
Instead of this:
var mediaUrl = item.entities.media.media_url_https;
try this:
var mediaUrl = item.entities.media[0].media_url_https;
as media is an array and could contain more than 1 item, so you'll need to specify the index.

how do I fetch the second level array values in JSON data using jQuery each()

I would like to select a particular value using jquery each from the second and third level array. This is my JSON response looks like:
{
"events": [{
"id": 847843,
"name": "Strasbourg IG at Limoges CSP",
"timezone": "GMT",
"timezoneOffset": 0,
"time": 1401983400000,
"timeUtc": "2014-06-05T18:50:00+00:00",
"status": "live",
"wpRef": "847843",
"parentCategoryId": 22,
"parentCategoryName": "Basketball",
"categoryId": 7443,
"categoryName": "French Championnat Pro A ",
"racingEvent": null,
"raceNumber": null,
"marketCount": 3,
"prefix": null,
"nameSeparator": null,
"markets": [{
"id": 4943131,
"primitiveType": 2,
"primitiveName": "Head to Head",
"typeId": 36,
"name": "Head to Head",
"marketDescription": "Select the winner of the match.",
"marketRules": "Includes extra time.\r",
"eventNotices": null,
"autoHide": false,
"status": "live",
"bettingStatus": "enabled",
"period": "Fulltime",
"allowMultiple": true,
"betInRunTime": 0,
"track": null,
"weather": null,
"betTypes": [{
"id": 1,
"name": "Win",
"finishingOrder": null,
"products": []
}],
"selections": [{
"id": 288481048,
"betId": null,
"eventId": null,
"eventNumber": null,
"eventName": null,
"eventTime": null,
"position": null,
"name": "Strasbourg IG",
"prefix": "",
"mpId": 288481048,
"marketPosition": null,
"marketName": null,
"marketTypeName": null,
"marketSelectionId": null,
"marketSelectionName": null,
"categoryId": null,
"categoryName": null,
"parentCategoryId": null,
"parentCategoryName": null,
"maxBet": 0.00,
"scratched": false,
"winPrice": null,
"placePrice": null,
"finalWinPrice": null,
"finalPlacePrice": null,
"finalPrice": null,
"prices": [{
"betTypeId": 1,
"betTypeName": "Win",
"productId": null,
"productName": null,
"precisePrice": 2.6,
"usPrice": "+160",
"value": 2.60
}]
}, {
"id": 288481039,
"betId": null,
"eventId": null,
"eventNumber": null,
"eventName": null,
"eventTime": null,
"position": null,
"name": "Limoges CSP",
"prefix": "",
"mpId": 288481039,
"marketPosition": null,
"marketName": null,
"marketTypeName": null,
"marketSelectionId": null,
"marketSelectionName": null,
"categoryId": null,
"categoryName": null,
"parentCategoryId": null,
"parentCategoryName": null,
"maxBet": 0.00,
"scratched": false,
"winPrice": null,
"placePrice": null,
"finalWinPrice": null,
"finalPlacePrice": null,
"finalPrice": null,
"prices": [{
"betTypeId": 1,
"betTypeName": "Win",
"productId": null,
"productName": null,
"precisePrice": 1.44,
"usPrice": "-227",
"value": 1.44
}]
}]
}, {
"id": 4943134,
"primitiveType": 99,
"primitiveName": "Other",
"typeId": 1266,
"name": "Odd or Even Total",
"marketDescription": "Select whether the amount of points scored in the match will be an odd or even number (zero = even)\r\rIncludes overtime.",
"marketRules": "For this market zero will be deemed to be an even number.\r\rNo bonus bets.\r\rIncludes overtime.",
"eventNotices": null,
"autoHide": true,
"status": "live",
"bettingStatus": "enabled",
"period": "Fulltime",
"allowMultiple": true,
"betInRunTime": 0,
"track": null,
"weather": null,
"betTypes": [{
"id": 1,
"name": "Win",
"finishingOrder": null,
"products": []
}],
"selections": [{
"id": 288481066,
"betId": null,
"eventId": null,
"eventNumber": null,
"eventName": null,
"eventTime": null,
"position": null,
"name": "Even",
"prefix": "",
"mpId": 288481066,
"marketPosition": null,
"marketName": null,
"marketTypeName": null,
"marketSelectionId": null,
"marketSelectionName": null,
"categoryId": null,
"categoryName": null,
"parentCategoryId": null,
"parentCategoryName": null,
"maxBet": 0.00,
"scratched": false,
"winPrice": null,
"placePrice": null,
"finalWinPrice": null,
"finalPlacePrice": null,
"finalPrice": null,
"prices": [{
"betTypeId": 1,
"betTypeName": "Win",
"productId": null,
"productName": null,
"precisePrice": 1.85,
"usPrice": "-118",
"value": 1.85
}]
}, {
"id": 288481075,
"betId": null,
"eventId": null,
"eventNumber": null,
"eventName": null,
"eventTime": null,
"position": null,
"name": "Odd",
"prefix": "",
"mpId": 288481075,
"marketPosition": null,
"marketName": null,
"marketTypeName": null,
"marketSelectionId": null,
"marketSelectionName": null,
"categoryId": null,
"categoryName": null,
"parentCategoryId": null,
"parentCategoryName": null,
"maxBet": 0.00,
"scratched": false,
"winPrice": null,
"placePrice": null,
"finalWinPrice": null,
"finalPlacePrice": null,
"finalPrice": null,
"prices": [{
"betTypeId": 1,
"betTypeName": "Win",
"productId": null,
"productName": null,
"precisePrice": 1.85,
"usPrice": "-118",
"value": 1.85
}]
}]
}, {
"id": 4943137,
"primitiveType": 99,
"primitiveName": "Other",
"typeId": 1298,
"name": "Match Result",
"marketDescription": null,
"marketRules": null,
"eventNotices": null,
"autoHide": false,
"status": "live",
"bettingStatus": "enabled",
"period": "Fulltime",
"allowMultiple": true,
"betInRunTime": 0,
"track": null,
"weather": null,
"betTypes": [{
"id": 1,
"name": "Win",
"finishingOrder": null,
"products": []
}],
"selections": [{
"id": 288481102,
"betId": null,
"eventId": null,
"eventNumber": null,
"eventName": null,
"eventTime": null,
"position": null,
"name": "Strasbourg IG",
"prefix": "",
"mpId": 288481102,
"marketPosition": null,
"marketName": null,
"marketTypeName": null,
"marketSelectionId": null,
"marketSelectionName": null,
"categoryId": null,
"categoryName": null,
"parentCategoryId": null,
"parentCategoryName": null,
"maxBet": 0.00,
"scratched": false,
"winPrice": null,
"placePrice": null,
"finalWinPrice": null,
"finalPlacePrice": null,
"finalPrice": null,
"prices": [{
"betTypeId": 1,
"betTypeName": "Win",
"productId": null,
"productName": null,
"precisePrice": 2.63,
"usPrice": "+163",
"value": 2.63
}]
}, {
"id": 288481084,
"betId": null,
"eventId": null,
"eventNumber": null,
"eventName": null,
"eventTime": null,
"position": null,
"name": "Limoges CSP",
"prefix": "",
"mpId": 288481084,
"marketPosition": null,
"marketName": null,
"marketTypeName": null,
"marketSelectionId": null,
"marketSelectionName": null,
"categoryId": null,
"categoryName": null,
"parentCategoryId": null,
"parentCategoryName": null,
"maxBet": 0.00,
"scratched": false,
"winPrice": null,
"placePrice": null,
"finalWinPrice": null,
"finalPlacePrice": null,
"finalPrice": null,
"prices": [{
"betTypeId": 1,
"betTypeName": "Win",
"productId": null,
"productName": null,
"precisePrice": 1.5,
"usPrice": "-200",
"value": 1.50
}]
}, {
"id": 288481093,
"betId": null,
"eventId": null,
"eventNumber": null,
"eventName": null,
"eventTime": null,
"position": null,
"name": "Draw",
"prefix": "",
"mpId": 288481093,
"marketPosition": null,
"marketName": null,
"marketTypeName": null,
"marketSelectionId": null,
"marketSelectionName": null,
"categoryId": null,
"categoryName": null,
"parentCategoryId": null,
"parentCategoryName": null,
"maxBet": 0.00,
"scratched": false,
"winPrice": null,
"placePrice": null,
"finalWinPrice": null,
"finalPlacePrice": null,
"finalPrice": null,
"prices": [{
"betTypeId": 1,
"betTypeName": "Win",
"productId": null,
"productName": null,
"precisePrice": 13.00,
"usPrice": "+1200",
"value": 13.00
}]
}]
}],
"result": null
}]
}
I am able to fetch all the "name" field from events category using the below code.
drawAllEvents: function (events) {
var $container = $('#someID ul');
$.each(events, function(i, event) {
$('<a />', { text: event.name, href: '#' }).wrap('<li />').parent().appendTo($container);
});
}
Now I am trying to fetch "primitiveName" field from the markets array using another function but for some reason it returns undefined. Here is my code
drawAllBetTypesFilter: function (events)  {
$('#bettype-sport ul').empty();
var betTypeFilter = $('#bettype-sport ul');
$.each(events, function (i, event) {
$.each(event.markets, function (market) {
var betTypeName = market.primitiveName;
$('<a />', {
text: betTypeName
}).wrap('<li />').parent().appendTo(betTypeFilter);
});
});
}
Furthermore, How do I fetch third level array, for e.g If I want to fetch all "name" fields under "betTypes" which is a child of "markets" object.
EDIT: 1 - Also mentioned in my comment. How do I group similar primitiveName values together in my list instead of displaying them seperately.
Here is the fiddle to show how am I fetching values in first level. FIDDLE LINK
The first parameter passed to the each() iteration function is the index of the current element in the array, so in your current code your market parameter is not the element from the array but instead an int. Try this:
var betTypeFilter = $('#bettype-sport ul');
$.each(events, function (i, event) {
$.each(event.markets, function (i, market) { // <- note 'i' first param
var betTypeName = market.primitiveName;
$('<a />', {
text: betTypeName
}).wrap('<li />').parent().appendTo(betTypeFilter);
// to get betTypes for this market:
$.each(market.betTypes, function(i, betType) {
// do something...
console.log(betType);
});
});
});
To fetch the name under betTypes would take another loop. Or, if there is only ever one object in the array you could hard-code access to the first element only:
market.betTypes[0].name; // == 'Win'
Alternatively, instead of using the jquery each function, why not just use traditional javascript looping. The $.each method isn't nearly as efficient as that.
drawAllBetTypesFilter: function (events) {
$('#bettype-sport ul').empty();
var betTypeFilter = $('#bettype-sport ul');
for(var i = 0; i < events.length; i++) {
var event = events[i];
for(var j = 0; j < event.markets.length; j++) {
var market = event.markets[j];
var betTypeName = market.primitiveName;
$('<a />', {
text: betTypeName
}).wrap('<li />').parent().appendTo(betTypeFilter);
};
};
}

Categories

Resources