Looping through nested JSON returns NULL - javascript

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?

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]}`);
}

Loop through JSON response and return values that matches another JSON response into a new key value

I have the following API call returned values that has an id value
var sites =
{
"response": [
{
"id": 1433,
"name": "Bronx 1",
"address": "5288 McGlynn Hills",
"latitude": 51.05,
"longitude": -114.066,
"time_zone": "Central Time (US & Canada)",
"units": "imperial",
"postal_code": null,
"city": null,
"state_province_region": null,
"country": null,
"rentable_area_from_lease": null,
"rentable_area_from_floors": 0,
"additional_site_common_area": 200,
"total_site_common_area": 200,
"site_attributes_url": "/api/1/sites/1433/attributes"
},
{
"id": 1434,
"name": "Bronx 2",
"address": "126 Mann Divide",
"latitude": 51.05,
"longitude": -114.066,
"time_zone": "Central Time (US & Canada)",
"units": "imperial",
"postal_code": null,
"city": null,
"state_province_region": null,
"country": null,
"rentable_area_from_lease": null,
"rentable_area_from_floors": 0,
"additional_site_common_area": 200,
"total_site_common_area": 200,
"site_attributes_url": "/api/1/sites/1434/attributes"
}
]
}
I need to use the ID value from the call above an compare it to the following API response site_id value
var floors =
{
"response": [
{
"id": 118,
"label": "Crowded floor",
"managed": true,
"unusable_area": 0,
"rentable_area": 100,
"site_common_area": 50,
"floor_common_area": 50,
"assigned_area": 0,
"image_url": "/GetFloorImage?z=118",
"site_id": 1433,
"icon_scale_factor": 0.2,
"floor_plan_images": [
{
"pixel_width": 2048,
"format": "png",
"coordinate_scale_factor": 2,
"url": "http://my-machine/api/1/floors/118/plan_image/2048.png"
},
{
"pixel_width": 4096,
"format": "png",
"coordinate_scale_factor": 4,
"url": "http://my-machine/api/1/floors/118/plan_image/4096.png"
}
],
"directories": [
"/api/1/directories/1390"
]
},
{
"id": 119,
"label": "Normal floor",
"managed": true,
"unusable_area": 0,
"rentable_area": 200,
"site_common_area": 0,
"floor_common_area": 200,
"assigned_area": 0,
"image_url": "/GetFloorImage?z=119",
"site_id": 1453,
"icon_scale_factor": 0.7,
"floor_plan_images": [
{
"pixel_width": 2048,
"format": "png",
"coordinate_scale_factor": 2,
"url": "http://my-machine/api/1/floors/119/plan_image/2048.png"
},
{
"pixel_width": 4096,
"format": "png",
"coordinate_scale_factor": 4,
"url": "http://my-machine/api/1/floors/119/plan_image/4096.png"
}
],
"directories": [
"/api/1/directories/1391"
]
}
],
"count": 2
}
When site.id = floors.site_id I want to build a new key value pair that looks like this: only for the matched values
var match {floor.id: site.name}
I am having trouble looping over both and returning values any help is appreciated
Thanks
Hey #Abdullah Albyati,
I try to created what u asked but, it's actually not that usefull but here it is:
var floors =
{
"response": [
{
"id": 118,
"label": "Crowded floor",
"managed": true,
"unusable_area": 0,
"rentable_area": 100,
"site_common_area": 50,
"floor_common_area": 50,
"assigned_area": 0,
"image_url": "/GetFloorImage?z=118",
"site_id": 1452,
"icon_scale_factor": 0.2,
"floor_plan_images": [
{
"pixel_width": 2048,
"format": "png",
"coordinate_scale_factor": 2,
"url": "http://my-machine/api/1/floors/118/plan_image/2048.png"
},
{
"pixel_width": 4096,
"format": "png",
"coordinate_scale_factor": 4,
"url": "http://my-machine/api/1/floors/118/plan_image/4096.png"
}
],
"directories": [
"/api/1/directories/1390"
]
},
{
"id": 119,
"label": "Normal floor",
"managed": true,
"unusable_area": 0,
"rentable_area": 200,
"site_common_area": 0,
"floor_common_area": 200,
"assigned_area": 0,
"image_url": "/GetFloorImage?z=119",
"site_id": 1453,
"icon_scale_factor": 0.7,
"floor_plan_images": [
{
"pixel_width": 2048,
"format": "png",
"coordinate_scale_factor": 2,
"url": "http://my-machine/api/1/floors/119/plan_image/2048.png"
},
{
"pixel_width": 4096,
"format": "png",
"coordinate_scale_factor": 4,
"url": "http://my-machine/api/1/floors/119/plan_image/4096.png"
}
],
"directories": [
"/api/1/directories/1391"
]
}
],
"count": 2
};
var sites =
{
"response": [
{
"id": 1433,
"name": "Bronx 1",
"address": "5288 McGlynn Hills",
"latitude": 51.05,
"longitude": -114.066,
"time_zone": "Central Time (US & Canada)",
"units": "imperial",
"postal_code": null,
"city": null,
"state_province_region": null,
"country": null,
"rentable_area_from_lease": null,
"rentable_area_from_floors": 0,
"additional_site_common_area": 200,
"total_site_common_area": 200,
"site_attributes_url": "/api/1/sites/1433/attributes"
},
{
// "id": 1434,
"id": 1453,
"name": "Bronx 2",
"address": "126 Mann Divide",
"latitude": 51.05,
"longitude": -114.066,
"time_zone": "Central Time (US & Canada)",
"units": "imperial",
"postal_code": null,
"city": null,
"state_province_region": null,
"country": null,
"rentable_area_from_lease": null,
"rentable_area_from_floors": 0,
"additional_site_common_area": 200,
"total_site_common_area": 200,
"site_attributes_url": "/api/1/sites/1434/attributes"
}
]
}
var conbined = floors.response.reduce((obj, floor) => {
var site_id = floor.site_id;
var site = sites.response.find(site => site.id === site_id);
if(site) {
console.log(site.name);
return { ...obj, floor_site_id: site.name }
}
return obj;
}, {});
console.log(conbined);
In the data you gave there was no data to combine so i changed one of the id's. Hope this works for you 😊

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 read jsonp response

I have a json file (http://example.com/usr/details?jsonp=parseRespond ) on a another server that gives the response
{
"id": "5572a7d648b33a462d79145d",
"avatarHash": null,
"bio": "",
"bioData": null,
"confirmed": false,
"fullName": "Ender Widgin",
"idPremOrgsAdmin": null,
"initials": "EW",
"memberType": "normal",
"products": [],
"status": "disconnected",
"url": "https://example.com/enderwidgin",
"username": "enderwidgin",
"avatarSource": null,
"email": null,
"gravatarHash": null,
"idBoards": [],
"idOrganizations": [],
"loginTypes": null,
"oneTimeMessagesDismissed": null,
"prefs": null,
"trophies": [],
"uploadedAvatarHash": null,
"premiumFeatures": [],
"idBoardsPinned": null,
"organizations": [],
"boards": [],
"actions": []
}
How can I write this response in a div
function parseRespond(){
// how to get the data ?
}
Thanks in advance!
JSON.parse may be helpful,
function parseRespond(response){
response = JSON.parse(response);
}

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