Related
I'm trying to return the uuid where the urns key has this match.
"urns": [
"whatsapp:27820111111"
],
What should be returned d7b9f88c-b359-4d69-926d-536c0d2892e0 since it has that phone number match. How can this be done programmatically.
Here's are the two dicts.
{
"next": "https://random.com=",
"previous": null,
"results": [
{
"uuid": "g2ws8dh5-b359-4d69-926d-536c0d2892e0",
"name": "James",
"language": "eng",
"urns": [
"whatsapp:27333333333"
],
"groups": [
{
"uuid": "57fs8430-3c78-42b7-876c-c385e36c1dba",
"name": "Postbirth WhatsApp"
}
],
"fields": {
"whatsapp_consent": null,
"webhook_failure_count": null,
},
"blocked": false,
"stopped": false,
"created_on": "2020-12-01T07:50:58.736502Z",
"modified_on": "2020-12-01T08:36:34.980359Z"
},
{
"uuid": "d7b9f88c-b359-4d69-926d-536c0d2892e0",
"name": "Jane",
"language": "eng",
"urns": [
"whatsapp:27820111111"
],
"groups": [
{
"uuid": "e35f2e39-3c78-42b7-876c-c385e36c1dba",
"name": "Prebirth WhatsApp"
}
],
"fields": {
"whatsapp_consent": null,
"webhook_failure_count": null,
},
"blocked": false,
"stopped": false,
"created_on": "2020-12-01T07:50:58.736502Z",
"modified_on": "2020-12-01T08:36:34.980359Z"
}
]
}
I'm able to loop through and find the urn but I'm not sure how to step back to get the uuid.
Pass in the results array and the urn string to this function. If found it will return the uuid, else it will return null.
function getIdFromUrn(results, urn) {
for (let i = 0; i < results.length; i++) {
const result = results[i];
if (result.urns.includes(urn)) {
return result.uuid; // urn found
}
}
return null; // not found
}
console.log(getIdFromUrn(results, 'whatsapp:27820111111'));
You don't need to loop when you can use find(...) to match against a value.
See demo below
var data = [{
"uuid": "g2ws8dh5-b359-4d69-926d-536c0d2892e0",
"name": "James",
"language": "eng",
"urns": [
"whatsapp:27333333333"
],
"groups": [{
"uuid": "57fs8430-3c78-42b7-876c-c385e36c1dba",
"name": "Postbirth WhatsApp"
}],
"fields": {
"whatsapp_consent": null,
"webhook_failure_count": null,
},
"blocked": false,
"stopped": false,
"created_on": "2020-12-01T07:50:58.736502Z",
"modified_on": "2020-12-01T08:36:34.980359Z"
},
{
"uuid": "d7b9f88c-b359-4d69-926d-536c0d2892e0",
"name": "Jane",
"language": "eng",
"urns": [
"whatsapp:27820111111"
],
"groups": [{
"uuid": "e35f2e39-3c78-42b7-876c-c385e36c1dba",
"name": "Prebirth WhatsApp"
}],
"fields": {
"whatsapp_consent": null,
"webhook_failure_count": null,
},
"blocked": false,
"stopped": false,
"created_on": "2020-12-01T07:50:58.736502Z",
"modified_on": "2020-12-01T08:36:34.980359Z"
}
];
const lookingFor = "whatsapp:27820111111";
const foundIt = data.find(el => {
return (el.urns.indexOf(lookingFor) !== -1);
});
console.log(foundIt.uuid);
I have a result set returned from a mongodb query and am using lodash to reformat it. I am trying to convert the array of objects into a single object. The problem is when I use lodash on the result set, I get unexpected output.
NOTE: Running the snippet on codepen/codesandbox gives correct output, but not when used directly from mongoose results.
Mongoose Query
try {
const petInfo = await pets.find({ userId: user_id, petId: pet_id })
.select({
"_id": 0,
"createdAt": 0,
"updatedAt": 0,
"__v": 0
});
if(!petInfo) {
return res.status(400).json({ message: "FAILED_TO_FETCH_PET_INFO" });
}
let newObj = _.reduce(petInfo, (acc, cur)=> { return _.assign(acc, cur) }, {});
return res.status(200).json(newObj);
}
catch (error) {
req.errorMsg = error.message; // Log actual error
return res.status(500).json({ message: "SOME_ERROR_OCCURRED" });
}
Result from mongoose find query (petInfo)
[
{
"age": {
"days": "",
"months": "",
"years": ""
},
"userId": "45422605180207851194",
"name": "Oscar",
"gender": "FEMALE",
"type": "Dog",
"breed": "",
"weight": "",
"spayOrNeuter": false,
"petId": "KSVv7yJLnUWX3n"
}
]
Lodash snippet
let newObj = _.reduce(petInfo, (acc, cur)=> { return _.assign(acc, cur) }, {});
return res.status(200).json(newObj);
Result after modification
{
"$__": {
"strictMode": true,
"selected": {
"_id": 0,
"createdAt": 0,
"updatedAt": 0,
"__v": 0
},
"getters": {
"age": {
"days": "",
"months": "",
"years": ""
}
},
"wasPopulated": false,
"scope": {
"age": {
"days": "",
"months": "",
"years": ""
},
"userId": "45422605180207851194",
"name": "Oscar",
"gender": "FEMALE",
"type": "Dog",
"breed": "",
"weight": "",
"spayOrNeuter": false,
"petId": "KSVv7yJLnUWX3n"
},
"activePaths": {
"paths": {
"userId": "init",
"petId": "init",
"name": "init",
"gender": "init",
"type": "init",
"breed": "init",
"age.days": "init",
"age.months": "init",
"age.years": "init",
"weight": "init",
"spayOrNeuter": "init"
},
"states": {
"ignore": {},
"default": {},
"init": {
"userId": true,
"name": true,
"gender": true,
"type": true,
"breed": true,
"age.days": true,
"age.months": true,
"age.years": true,
"weight": true,
"spayOrNeuter": true,
"petId": true
},
"modify": {},
"require": {}
},
"stateNames": [
"require",
"modify",
"init",
"default",
"ignore"
]
},
"pathsToScopes": {},
"cachedRequired": {},
"session": null,
"$setCalled": {},
"emitter": {
"_events": {},
"_eventsCount": 0,
"_maxListeners": 0
},
"$options": {
"skipId": true,
"isNew": false,
"willInit": true
},
"nestedPath": "age"
},
"isNew": false,
"_doc": {
"age": {
"days": "",
"months": "",
"years": ""
},
"userId": "45422605180207851194",
"name": "Oscar",
"gender": "FEMALE",
"type": "Dog",
"breed": "",
"weight": "",
"spayOrNeuter": false,
"petId": "KSVv7yJLnUWX3n"
},
"$locals": {},
"$init": true
}
The reason for this is because mongoose doesn't return the object you think it does. Instead, it returns a 'mongoose' object with a bunch of methods ect ect. There are 2 ways around this, either call .lean() on your query or toJSON() on the result to sanitize result into normal js object.
.lean()
const petInfo = await pets.find({ userId: user_id, petId: pet_id })
.select({
"_id": 0,
"createdAt": 0,
"updatedAt": 0,
"__v": 0
}).lean();
.toJSON()
const petInfo = await pets.find({ userId: user_id, petId: pet_id })
.select({
"_id": 0,
"createdAt": 0,
"updatedAt": 0,
"__v": 0
}).lean();
const parsed = petInfo.toJSON()
Your query will return the result set as document objects instead of plain objects, which is why you get all the additional information like strictMode, getters, etc.
You could use the lean() function in order to get plain objects only (see https://mongoosejs.com/docs/tutorials/lean.html), e.g.:
const petInfo = await pets.find({ userId: user_id, petId: pet_id })
.select({
"_id": 0,
"createdAt": 0,
"updatedAt": 0,
"__v": 0
}).lean();
I am trying to get Name, Node Name and Phase values from JSON Data using JavaScript. Here is my JavaScript
<script>
$(document).ready(function () {
$.getJSON('http://ec2-3-82-117-70.compute-1.amazonaws.com:8080/api/v0/retrievePodStatus/default',
function (data) {
console.log(data)
document.body.append("Name: " + data.items[1].metadata.name);
// document.body.append(data.items[1].metadata.name);
// document.body.append(data.items[0].spec.nodeName);
});
});
</script>
I am just getting the name in here. Can someone please help me how to get Name, Node Name and Phase Values? find the below JSON as well.
"apiVersion": "v1",
"items": [
{
"apiVersion": "v1",
"kind": "Pod",
"metadata": {
"annotations": {
"kubernetes.io/limit-ranger": "LimitRanger plugin set: cpu request for container external-dns"
},
"creationTimestamp": "2019-02-28T16:22:49Z",
"generateName": "external-dns-5d69b66646-",
"labels": {
"app": "external-dns",
"pod-template-hash": "1825622202"
},
"name": "external-dns-5d69b66646-pmxmd",
"namespace": "default",
"ownerReferences": [
{
"apiVersion": "extensions/v1beta1",
"blockOwnerDeletion": true,
"controller": true,
"kind": "ReplicaSet",
"name": "external-dns-5d69b66646",
"uid": "170d9260-3b75-11e9-abe2-0ec5819342ce"
}
],
"resourceVersion": "2984",
"selfLink": "/api/v1/namespaces/default/pods/external-dns-5d69b66646-pmxmd",
"uid": "170e1a0d-3b75-11e9-abe2-0ec5819342ce"
},
"spec": {
"containers": [
{
"args": [
"--source=service",
"--source=ingress",
"--provider=aws",
"--registry=txt",
"--txt-owner-id=qpair"
],
"image": "registry.opensource.zalan.do/teapot/external-dns:v0.4.2",
"imagePullPolicy": "IfNotPresent",
"name": "external-dns",
"resources": {
"requests": {
"cpu": "100m"
}
},
"terminationMessagePath": "/dev/termination-log",
"terminationMessagePolicy": "File",
"volumeMounts": [
{
"mountPath": "/var/run/secrets/kubernetes.io/serviceaccount",
"name": "default-token-rr546",
"readOnly": true
}
]
}
],
"dnsPolicy": "ClusterFirst",
"nodeName": "ip-172-20-39-147.ec2.internal",
"restartPolicy": "Always",
"schedulerName": "default-scheduler",
"securityContext": {},
"serviceAccount": "default",
"serviceAccountName": "default",
"terminationGracePeriodSeconds": 30,
"tolerations": [
{
"effect": "NoExecute",
"key": "node.kubernetes.io/not-ready",
"operator": "Exists",
"tolerationSeconds": 300
},
{
"effect": "NoExecute",
"key": "node.kubernetes.io/unreachable",
"operator": "Exists",
"tolerationSeconds": 300
}
],
"volumes": [
{
"name": "default-token-rr546",
"secret": {
"defaultMode": 420,
"secretName": "default-token-rr546"
}
}
]
},
"status": {
"conditions": [
{
"lastProbeTime": null,
"lastTransitionTime": "2019-02-28T16:22:49Z",
"status": "True",
"type": "Initialized"
},
{
"lastProbeTime": null,
"lastTransitionTime": "2019-02-28T16:22:58Z",
"status": "True",
"type": "Ready"
},
{
"lastProbeTime": null,
"lastTransitionTime": "2019-02-28T16:22:49Z",
"status": "True",
"type": "PodScheduled"
}
],
"containerStatuses": [
{
"containerID": "docker://18b96317cf360d562fb3f849c6716c50a41a67a4dbc126164020531e1e4d84a9",
"image": "registry.opensource.zalan.do/teapot/external-dns:v0.4.2",
"imageID": "docker-pullable://registry.opensource.zalan.do/teapot/external-dns#sha256:d54b9eb8948b87eb7fcd938990ff2dbc9ca0a42d9c5d36fcaa75c7cf066f7995",
"lastState": {},
"name": "external-dns",
"ready": true,
"restartCount": 0,
"state": {
"running": {
"startedAt": "2019-02-28T16:22:57Z"
}
}
}
],
"hostIP": "172.20.39.147",
"phase": "Running",
"podIP": "100.96.7.3",
"qosClass": "Burstable",
"startTime": "2019-02-28T16:22:49Z"
}
},
I am just getting the name in here. Can someone please help me how to get Name, Node Name and Phase Values? find the below JSON as well.
Thanks, Much Appreciated
You were close with the code you posted. You just needed items[0] instead of items[1]. Remember the first element of an array is always 0. Other than that its as easy as checking the open and close brackets [] or {} to see where each nested object/array starts and ends.
Code:
var name = data.items[0].metadata.name
var nodeName = data.items[0].spec.nodeName
var phase = data.items[0].status.phase
snippet:
var data = {
"apiVersion": "v1",
"items": [{
"apiVersion": "v1",
"kind": "Pod",
"metadata": {
"annotations": {
"kubernetes.io/limit-ranger": "LimitRanger plugin set: cpu request for container external-dns"
},
"creationTimestamp": "2019-02-28T16:22:49Z",
"generateName": "external-dns-5d69b66646-",
"labels": {
"app": "external-dns",
"pod-template-hash": "1825622202"
},
"name": "external-dns-5d69b66646-pmxmd",
"namespace": "default",
"ownerReferences": [{
"apiVersion": "extensions/v1beta1",
"blockOwnerDeletion": true,
"controller": true,
"kind": "ReplicaSet",
"name": "external-dns-5d69b66646",
"uid": "170d9260-3b75-11e9-abe2-0ec5819342ce"
}],
"resourceVersion": "2984",
"selfLink": "/api/v1/namespaces/default/pods/external-dns-5d69b66646-pmxmd",
"uid": "170e1a0d-3b75-11e9-abe2-0ec5819342ce"
},
"spec": {
"containers": [{
"args": [
"--source=service",
"--source=ingress",
"--provider=aws",
"--registry=txt",
"--txt-owner-id=qpair"
],
"image": "registry.opensource.zalan.do/teapot/external-dns:v0.4.2",
"imagePullPolicy": "IfNotPresent",
"name": "external-dns",
"resources": {
"requests": {
"cpu": "100m"
}
},
"terminationMessagePath": "/dev/termination-log",
"terminationMessagePolicy": "File",
"volumeMounts": [{
"mountPath": "/var/run/secrets/kubernetes.io/serviceaccount",
"name": "default-token-rr546",
"readOnly": true
}]
}],
"dnsPolicy": "ClusterFirst",
"nodeName": "ip-172-20-39-147.ec2.internal",
"restartPolicy": "Always",
"schedulerName": "default-scheduler",
"securityContext": {},
"serviceAccount": "default",
"serviceAccountName": "default",
"terminationGracePeriodSeconds": 30,
"tolerations": [{
"effect": "NoExecute",
"key": "node.kubernetes.io/not-ready",
"operator": "Exists",
"tolerationSeconds": 300
},
{
"effect": "NoExecute",
"key": "node.kubernetes.io/unreachable",
"operator": "Exists",
"tolerationSeconds": 300
}
],
"volumes": [{
"name": "default-token-rr546",
"secret": {
"defaultMode": 420,
"secretName": "default-token-rr546"
}
}]
},
"status": {
"conditions": [{
"lastProbeTime": null,
"lastTransitionTime": "2019-02-28T16:22:49Z",
"status": "True",
"type": "Initialized"
},
{
"lastProbeTime": null,
"lastTransitionTime": "2019-02-28T16:22:58Z",
"status": "True",
"type": "Ready"
},
{
"lastProbeTime": null,
"lastTransitionTime": "2019-02-28T16:22:49Z",
"status": "True",
"type": "PodScheduled"
}
],
"containerStatuses": [{
"containerID": "docker://18b96317cf360d562fb3f849c6716c50a41a67a4dbc126164020531e1e4d84a9",
"image": "registry.opensource.zalan.do/teapot/external-dns:v0.4.2",
"imageID": "docker-pullable://registry.opensource.zalan.do/teapot/external-dns#sha256:d54b9eb8948b87eb7fcd938990ff2dbc9ca0a42d9c5d36fcaa75c7cf066f7995",
"lastState": {},
"name": "external-dns",
"ready": true,
"restartCount": 0,
"state": {
"running": {
"startedAt": "2019-02-28T16:22:57Z"
}
}
}],
"hostIP": "172.20.39.147",
"phase": "Running",
"podIP": "100.96.7.3",
"qosClass": "Burstable",
"startTime": "2019-02-28T16:22:49Z"
}
}],
}
var name = data.items[0].metadata.name
var nodeName = data.items[0].spec.nodeName
var phase = data.items[0].status.phase
console.log(name)
console.log(nodeName)
console.log(phase)
SO I have this setting json
[{
"name": "Business",
"skip": "0",
"pos": "1"
},
{
"name": "contact",
"skip": "1",
"pos": "3"
},
{
"name": "UKSite",
"skip": "0",
"pos": "2"
}
]
Then I have my data json
[{
"name": "contact",
"hideShow": true,
"data": {
"con_title": "Sri",
"con_fName": "Jhon",
"con_lName": "Snow",
"emails": ["maheshwar#hsjsk.com", ""],
"phones": ["8867116216", ""]
},
"repeatable": false
}, {
"name": "UKAddress",
"hideShow": true,
"data": {
"addAddress": [{
"add_bilding_num": "BUILDING NAME/NUMBER",
"add_street_name": "STREET",
"add_town": "TOWN",
"add_county": "COUNTY",
"add_pc": "POST CODE",
"add_type": "TYPE"
}, {
"add_bilding_num": "BUILDING NAME/NUMBER",
"add_street_name": "STREET",
"add_town": "TOWN",
"add_county": "COUNTY",
"add_pc": "POST CODE",
"add_type": "TYPE"
}]
},
"repeatable": false
}, {
"name": "Business",
"hideShow": true,
"data": {
"biss_name": "Nano Corporation"
},
"repeatable": false
}, {
"name": "contact",
"hideShow": true,
"data": {
"con_title": "Mr",
"con_fName": "Roshan",
"con_lName": "Aslam",
"emails": ["roshan#throughbit.com"],
"phones": ["8867116216"]
},
"repeatable": true
}, {
"name": "UKSite",
"hideShow": true,
"data": {
"site_name": "naonocrporation.co.uk",
"external_rff": "fsfsfs",
"con_title": "Mr",
"con_fName": "Kash",
"con_lName": "Sangh",
"emails": ["kash#youremail.com"],
"phones": ["8867116216"],
"addAddress": [{
"add_bilding_num": "",
"add_street_name": "",
"add_town": "",
"add_county": "",
"add_pc": "",
"add_type": ""
}],
"ElecMeter": [{
"distrib_id": "DISTRIBUTOR ID",
"pc": "PROFILE CLASS",
"mtc": "METER TIMESWITCH CODE",
"llf": "LINE LOSS FACTOR",
"mpc": "MPAN CORE",
"eac": "EAC",
"c_supplr": "CURRENT SUPPLIER",
"c_date": "CURRENT END DATE",
"select": true
}, {
"distrib_id": "",
"pc": "",
"mtc": "",
"llf": "",
"mpc": "",
"eac": "",
"c_supplr": "",
"c_date": ""
}],
"GasMeter": [{
"mprn": "MPRN",
"aq": "AQ",
"g_c_supplr": "CURRENT SUPPLIER",
"g_c_date": "CURRENT END DATE"
}]
},
"repeatable": true
}]
I have to loop on the data json and using the information from setting json need to create a new Json
for example
my new json should look like this
[{
"name": "Business",
"hideShow": true,
"data": {
"biss_name": "Nano Corporation"
},
"repeatable": false
},
{
"name": "contact",
"hideShow": true,
"data": {
"con_title": "Mr",
"con_fName": "Roshan",
"con_lName": "Aslam",
"emails": [
"roshan#throughbit.com"
],
"phones": [
"8867116216"
]
},
"repeatable": true
},
{
"name": "UKAddress",
"hideShow": true,
"data": {
"addAddress": [{
"add_bilding_num": "BUILDING NAME/NUMBER",
"add_street_name": "STREET",
"add_town": "TOWN",
"add_county": "COUNTY",
"add_pc": "POST CODE",
"add_type": "TYPE"
},
{
"add_bilding_num": "BUILDING NAME/NUMBER",
"add_street_name": "STREET",
"add_town": "TOWN",
"add_county": "COUNTY",
"add_pc": "POST CODE",
"add_type": "TYPE"
}
]
},
"repeatable": false
}
]
You can Observe , The term skip:1 which means skip the first one and add rest also the terminology pos:1 which is telling what should be the position of the object in the new array.
Any help would be great
Update 1
I came up with this snippet
ar finalArray = []
for(var i = 0; i < b.length; i++){
var counter = 0;
for(var j = 0; j < a.length; j++){
if(b[i].name == a[j].name){
if(counter < b[i].skip){
counter++;
continue;
}
finalArray.push(a[j])
}
}
}
Thanks
As you are dealing with an array of objects and you want to modify each one during the iteration based on conditions, I'd recommend you to use forEach
You have docs and examples here:
https://developer.mozilla.org/es/docs/Web/JavaScript/Referencia/Objetos_globales/Array/map
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