Parse JSON with multiple levels - javascript

I am trying to parse this JSON that I have assigned to a javascript variable but I am having a hard time looping through it due to it having multiple levels
<script type="text/javascript">
var varJson = {
"d": {
"results": [
{
"__metadata": {
"id": "http://www.bradinsight.com/ALFAPI/AlfWebApi/Offices(100013449)",
"uri": "http://www.bradinsight.com/ALFAPI/AlfWebApi/Offices(100013449)",
"type": "AlfWebApiInfrastructure.Poco.Office"
},
"Agency": {
"__deferred": {
"uri": "http://www.bradinsight.com/ALFAPI/AlfWebApi/Offices(100013449)/Agency"
}
},
"Advertiser": {
"__deferred": {
"uri": "http://www.bradinsight.com/ALFAPI/AlfWebApi/Offices(100013449)/Advertiser"
}
},
"Contacts": {
"results": [
{
"__metadata": {
"id": "http://www.bradinsight.com/ALFAPI/AlfWebApi/Contacts(id=59980,jobId=1000105450)",
"uri": "http://www.bradinsight.com/ALFAPI/AlfWebApi/Contacts(id=59980,jobId=1000105450)",
"type": "AlfWebApiInfrastructure.Poco.Contact"
},
"id": 59980,
"jobId": 1000105450,
"mask": 67108863,
"name": "Name",
"jobtitle": "Job Title",
"email": "email",
"companyType": "companyType",
"companyId": 1787,
"officeId": 100013449,
"address1": "address1",
"address2": "",
"address3": "",
"address4": "",
"addressTown": "addressTown",
"addressPostCode": "addressPostCode",
"tel": "tel",
"fax": "fax",
"responsibilities": "responsibilities"
},
{
"__metadata": {
"id": "http://www.bradinsight.com/ALFAPI/AlfWebApi/Contacts(id=64085,jobId=1000105448)",
"uri": "http://www.bradinsight.com/ALFAPI/AlfWebApi/Contacts(id=64085,jobId=1000105448)",
"type": "AlfWebApiInfrastructure.Poco.Contact"
},
"id": 64085,
"jobId": 1000105448,
"mask": 67108863,
"name": "name",
"jobtitle": "jobtitle",
"email": "email",
"companyType": "companyType",
"companyId": 1787,
"officeId": 100013449,
"address1": "address1",
"address2": "",
"address3": "",
"address4": "",
"addressTown": "addressTown",
"addressPostCode": "addressPostCode",
"tel": "tel",
"fax": "fax",
"responsibilities": "responsibilities"
}
]
},
"id": 100013449,
"companyId": 1787,
"addressLine1": "addressLine1",
"addressLine2": "",
"addressLine3": "",
"addressLine4": "",
"addressLine5": "addressLine5",
"postCode": "postCode",
"regionId": "regionId",
"countyId": "countyId",
"tvAreaId": "L",
"telephone": "telephone",
"fax": "fax8",
"countryId": "countryId",
"email": "email",
"isdn": null,
"mask": 66060287
}
]
}
};
$(document).ready(function () {
//var parsed = JSON.parse(varJson);
alert(varJson);
});
</script>
I tried using this:
$.each(varJson, function (index, item) {
alert(item);
});
But it just says object in my alert.

try this,
function traverse(jsonObj) {
if( typeof jsonObj == "object" ) {
$.each(jsonObj, function(k,v) {
traverse(v);
});
}
else {
alert(jsonObj);
}
}
$(document).ready(function () {
traverse(varJson);
});
http://jsfiddle.net/satpalsingh/hXEr8/
with reference of Traverse all the Nodes of a JSON Object Tree with JavaScript

You don't need to parse it in your example.
Use console.log instead of alert and you will the the object in your web inspector.
If you do want to alert do something like this
alert(varJson.d.results[0].__metadata.id)

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

filter nest array of object using java script

This the data i need this value only email": "gm#gmail.com"
{
"params": {
"user": {
"address1": "790 7th Ave",
"address2": "hhhdkhdskhsdkh",
"city": "Chennai",
"name": "gm4",
"phone": "",
"state": "TN",
"zipcode": "600008"
},
"query": {
"FILTERS": [
[
{
"EQ": {
"email": "gm#gmail.com"
}
}
]
],
"PAGENUM": 1,
"PAGESIZE": 100,
"SELECTCOLUMNS": [],
"SORT": []
},
"trigger": "User::UserUpdated"
},
"context": {}
}
actually, I tried const out = req.params.query.FILTERS[0].EQ.email
but i field unable to get expect result plz help.
It is a nested array.
req.params.query.FILTERS[0][0].EQ.email

Parse json array and loop through all the data for Pivot.js

I have a json array data in this format:
{
"jobs": [
{
"id": "some_random_id_1",
"email": "some#email.com",
"email_type": "html",
"status": "pending",
"job_fields": {
"TITLE": "job title here"
},
"stats": {
"applied": 40,
"rejected": 20
}
},
{
"id": "some_random_id_2",
"email": "some#email.com",
"email_type": "html",
"status": "pending",
"job_fields": {
"TITLE": "job title here"
},
"stats": {
"applied": 30,
"rejected": 20
}
},
{
"id": "some_random_id_3",
"email": "some#email.com",
"email_type": "html",
"status": "pending",
"job_fields": {
"TITLE": "job title here"
},
"stats": {
"applied": 13,
"rejected": 1
}
},
{
"id": "some_random_id_4",
"email": "some#email.com",
"email_type": "html",
"status": "pending",
"job_fields": {
"TITLE": "job title here"
},
"stats": {
"applied": 13,
"rejected": 1
}
}
],
"job_id": "some_id",
"total_jobs": 60
}
where I just need to access the jobs object and grab id and status and all info for job_fields and stats (or all info for now).
// example is from here
// https://pivottable.js.org/examples/mps.html
$(function(){
$.getJSON("data.json", function(mps) {
$("#output").pivotUI(mps);
});
});
the example works with this json format:
[{
"Province": "Quebec",
"Party": "NDP",
"Age": 22,
"Name": "Liu, Laurin",
"Gender": "Female"
},
{
"Province": "Quebec",
"Party": "Bloc Quebecois",
"Age": 43,
"Name": "Mourani, Maria",
"Gender": "Female"
},
{
"Province": "Ontario",
"Party": "Conservative",
"Age": "",
"Name": "O'Toole, Erin",
"Gender": "Male"
}
]
I am not sure how to modify the javascript so it can read my json format. I can't modify the json format to match the above format, so in the above javascript example, province, party, etc are all passed to the function.
I want to do the same but with my json format, so output id, status, all members of job_fields (ex: TITLE, etc. ), all members of stats (ex: applied, rejected.
Assuming all jobs have job_fields.TITLE, stats.applied and stats.rejected maybe the following will do:
const json = {
"jobs": [
{
"id": "some_random_id_1",
"email": "some#email.com",
"email_type": "html",
"status": "pending",
"job_fields": {
"TITLE": "job title here"
},
"stats": {
"applied": 40,
"rejected": 20
}
},
{
"id": "some_random_id_2",
"email": "some#email.com",
"email_type": "html",
"status": "pending",
"job_fields": {
"TITLE": "job title here"
},
"stats": {
"applied": 30,
"rejected": 20
}
},
{
"id": "some_random_id_3",
"email": "some#email.com",
"email_type": "html",
"status": "pending",
"job_fields": {
"TITLE": "job title here"
},
"stats": {
"applied": 13,
"rejected": 1
}
},
{
"id": "some_random_id_4",
"email": "some#email.com",
"email_type": "html",
"status": "pending",
"job_fields": {
"TITLE": "job title here"
},
"stats": {
"applied": 13,
"rejected": 1
}
}
],
"job_id": "some_id",
"total_jobs": 60
};
console.log(
json.jobs.map(
(job)=>({
id:job.id,
status:job.status,
title:job.job_fields.TITLE,
applied:job.stats.applied,
rejected:job.stats.rejected
})
)
);
You can use map and use Object.assign and spread operator to make an object
var obj={"jobs":[{"id":"some_random_id_1","email":"some#email.com","email_type":"html","status":"pending","job_fields":{"TITLE":"job title here"},"stats":{"applied":40,"rejected":20}},{"id":"some_random_id_2","email":"some#email.com","email_type":"html","status":"pending","job_fields":{"TITLE":"job title here"},"stats":{"applied":30,"rejected":20}},{"id":"some_random_id_3","email":"some#email.com","email_type":"html","status":"pending","job_fields":{"TITLE":"job title here"},"stats":{"applied":13,"rejected":1}},{"id":"some_random_id_4","email":"some#email.com","email_type":"html","status":"pending","job_fields":{"TITLE":"job title here"},"stats":{"applied":13,"rejected":1}}],"job_id":"some_id","total_jobs":60}
var result = obj.jobs.map(({id,status,job_fields,stats}) => {
return Object.assign({}, {id}, {status}, {...job_fields}, {...stats});
});
console.log(result);
Or you can make it shorter like:
var result = obj.jobs.map( ({id,status,job_fields,stats}) => Object.assign({},{id},{status},{...job_fields},{...stats}) );
Can try with below snippet:
$(function(){
$.getJSON("data.json", function(orgData) {
var pivotData = [];
orgData.jobs.forEach(function (job, ind) {
var reqInfo = {};
reqInfo['id'] = job.id;
reqInfo['status'] = job.status;
reqInfo['jobTitle'] = job.job_fields && job.job_fields.TITLE;
reqInfo['applied'] = job.stats && job.stats.applied;
reqInfo['rejected'] = job.stats && job.stats.rejected;
pivotData.push(reqInfo)
})
$("#output").pivotUI(pivotData);
});
});
$("#output").pivotUI(mps.jobs);

jQuery autocomplate parse specific array of data from json object

I have some problem with here jquery here. So I want to make an autocomplete text field using json object from database, here I provide my code
jQuery :
$('#school_name').autocomplete({
minLength: 3,
autoFocus: true,
source: function(request, response) {
$.getJSON('https://host/path', { q: $('#school_name').val() },
response);
}
Return Json
{
"status": "success",
"result": {
"data": [
{
"school_id": xxx,
"school_name": "xxx",
"status": "Swasta",
"address": "xxx",
"city": "BANYUWANGI",
"province": "JAWA TIMUR",
"phone": "1234",
"email": "xx#a.co",
"picture": null,
"is_published": "Y"
},
{
"school_id": xxx,
"school_name": "xxx",
"status": "Swasta",
"address": " ",
"city": "",
"province": "",
"phone": "-",
"email": null,
"picture": null,
"is_published": "Y"
}
]
}
}
I dont want return value json object like i've got, I only need school_name in array form, please help me to solve my problem
Use response callback to push data you want.
$('#school_name').autocomplete({
minLength: 3,
autoFocus: true,
source: function(request, response) {
$.get('https://host/path').always(function(res) {
var json = JSON.parse(res), result_arr = [];
$.each(json.result.data, function(k,v) {
result_arr.push(v.school_name);
});
response(result_arr);
});
}
});
You can use Array.prototype.map to transform an array. map will run a function over each item in the array and create a new array with the returned values.
const json = {
"status": "success",
"result": {
"data": [
{
"school_id": '1234',
"school_name": "First School Name",
"status": "Swasta",
"address": "xxx",
"city": "BANYUWANGI",
"province": "JAWA TIMUR",
"phone": "1234",
"email": "xx#a.co",
"picture": null,
"is_published": "Y"
},
{
"school_id": '5678',
"school_name": "Second School Name",
"status": "Swasta",
"address": " ",
"city": "",
"province": "",
"phone": "-",
"email": null,
"picture": null,
"is_published": "Y"
}
]
}
}
console.log(
json.result.data.map(school => school.school_name)
)

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