Loop over Json using Jquery - javascript

Below is my Json Data received from Ajax response.
{
"error": {
"errorCode": "0001",
"errorText": "SUCCESS"
},
"responselist": [
{
"count": 2,
"event": [
{
"startDate": null,
"eventId": 1234,
"eventName": "Interview",
"modifiedUser": "User",
"eventTypeCode": "1",
"eventVenue": null,
"eventSpecialInst": "isnsdf",
"eventStatusCode": "OP",
"eventLangCode": "Eng",
"eventDesc": "sdfsadfsd",
"fromEmailId": "Abcd#apple.com",
"rsvpDeadline": 5,
"canceledInd": "yes",
"canceldEmailText": "sdfasdfasdfasfasdfasdfasdf",
"daysToWaitlistLastCall": 5,
"daysToReminderAdmin": 6,
"daysToReminderEvent": 3,
"daysToReminderInvitation": 2,
"endDate": null,
"venueAddrLine1": null,
"venueAddrLine2": null,
"venueAddrLine3": null,
"cityCode": null,
"stateCode": null,
"appId": null,
"modifiedDate": "2010-12-16",
"countryCode": null,
"zipCode": null,
"user_id": null,
"updateFlag": "R"
},
{
"startDate": null,
"eventId": 4321,
"eventName": "Seasonal Hiring",
"modifiedUser": "User",
"eventTypeCode": "1",
"eventVenue": null,
"eventSpecialInst": "isnsdf",
"eventStatusCode": "OP",
"eventLangCode": "Eng",
"eventDesc": "sdfsadfsd",
"fromEmailId": "Abcd#apple.com",
"rsvpDeadline": 5,
"canceledInd": "yes",
"canceldEmailText": "sdfasdfasdfasfasdfasdfasdf",
"daysToWaitlistLastCall": 5,
"daysToReminderAdmin": 6,
"daysToReminderEvent": 3,
"daysToReminderInvitation": 2,
"endDate": null,
"venueAddrLine1": "KFC",
"venueAddrLine2": "The Forum",
"venueAddrLine3": "Koramangala",
"cityCode": "Bangalore",
"stateCode": "Karnataka",
"appId": null,
"modifiedDate": "2010-12-16",
"countryCode": "India",
"zipCode": "560040",
"user_id": null,
"updateFlag": "R"
}
]
}
]
}
Using below code to extract information inside event object. But I am not able to do it. Need guidance.
$.ajax({ url:"<%=request.getContextPath()%>/service/showInvitedEvents/21",
dataType:"json",
success: function(jsonData)
{
alert("Inside response success");
$.each(jsonData.responselist.event,function(i,item)
$.each(Employees,function(i,item)
{
alert('Iteration is' + i);
var teventName = item.eventName;
var teventVenue = item.eventVenue;
var tstartDate = item.startDate;
var tendDate = item.endDate;
var tstarend = tstartDate +" - "+ tendDate ;
$("#eventTable tbody").append("<tr><td><a id="+teventName+i+" href=<%=request.getContextPath()%>/service/session/1234>"+teventName+"</a></td><td>"+teventVenue+"</td><td>"+tstarend+"</td></tr>");
});

First of all you can't loop over jsonData.responselist.event. jsonData.responselist is an array so either need to make a double loop or if you always know there is one and only one item in responslist you could loop over jsonData.responselist[0].event
For the rest of it I'm not sure why you have this row:
$.each(Employees,function(i,item)
Looks like a misstake to as it isn't valid there(the syntax is wrong and it hides both i and item from the real each).

What is the purpose of the following line in your code:?
$.each(Employees,function(i,item)
Try removing it and see what happens.

Related

How to get in angular sorted list in backend from response body?

I want to post in request body like this with sort criteria:
{
"page": {
"number": 0,
"size": 10
},
"searchSortCriteria": [
{
"key": "id",
"operation": "ASC"
}
]
}
Backend gives back already sorted list of expenses from response body like this:
{
"page": null,
"hasNextPage": false,
"totalPages": 1,
"expenses": [
{
"createdUser": null,
"updatedUser": null,
"createdDate": "2021-07-11T19:50:23",
"updatedDate": null,
"id": 4,
"user": "Radek",
"amount": 123,
"currency": "PLN",
"description": "Grocery",
"payDate": "2021-07-11",
"payMethod": {
"id": 2,
"payMethodName": "Cash"
},
"expenseCategory": {
"id": 1,
"categoryName": "Food at home"
}
},
{
"createdUser": null,
"updatedUser": null,
"createdDate": "2021-07-11T19:53:00",
"updatedDate": null,
"id": 5,
"user": "Agata",
"amount": 52,
"currency": "PLN",
"description": "toys",
"payDate": "2021-07-10",
"payMethod": {
"id": 1,
"payMethodName": "Credit card"
},
"expenseCategory": {
"id": 11,
"categoryName": "Other"
}
}
]
}
I know how to make proper request but I have a problem how to get the sorted list from response body. I'm looking for any method that can just extract from json in response body.
public findAllPost(criteriaRequest: ExpenseCriteriaRequest): Observable<ExpenseCriteriaRequest> {
return this.httpClient.post<ExpenseCriteriaRequest>(this.url, criteriaRequest, this.httpOptions);
}
ngOnInit(): void {
this.expenseService.findAllPost(this.criteriaRequest)
.subscribe(request => this.criteriaRequest = request);
}
I did it like this and works
public findAllPost(criteriaRequest: ExpenseCriteriaRequest): Observable<ResponseExpenses> {
return this.httpClient.post<ResponseExpenses>(this.url, criteriaRequest, this.httpOptions);
}
ngOnInit(): void {
this.expenseService.findAllPost(this.criteriaRequest)
.subscribe(response => this.responseExpenses = response);
}

Postman - Looping through an array of nested objects to make a variable

I am trying to set a variable from following phone number with value: “+33652556777” (index 4 in JSON attached below) which is the last object in contacts (index 4).
To do so is pretty simple:
let jsonData = pm.response.json();
console.log (jsonData.contacts[4].phone_numbers[0].value)
const PhoneNumber = jsonData.contacts[4].phone_numbers[0].value
pm.environment.set("Jacky", PhoneNumber);
Since I have to use different query parameters to filter by eg. created_at=asc, desc, the property of the phone_numbers order might change index number and I won’t be able to fetch desire phone number "+33652556777” instead it will set a different phone number which I cannot allow.
I know there is way to fetch our number and make it variable for next requests, which is iterating over properties or keys in the object “ for….in or for…of ” but for some reason I cannot achieve it.
What I could achieve is to get through first object “contacts” but impossible to get to its nested array “phone_numbers”. Here is how I did it:
let jsonData = pm.response.json();
let contact;
for (let filter of jsonData.contacts){
if (filter.last_name == "Rowland"){
contact = filter;
}}
console.log (contact);
Could you please help?
Here goes the JSON body response:
{
"contacts": [
{
"id": 11121211,
"direct_link": "https://example.example",
"first_name": "test1",
"last_name": "test",
"company_name": "test",
"information": null,
"is_shared": true,
"created_at": 1582798926,
"updated_at": 1582798926,
"emails": [],
"phone_numbers": [
{
"id": 60065270,
"label": "Work",
"value": "+33134567666"
}
]
},
{
"id": 22222222,
"direct_link": "https://example.example",
"first_name": null,
"last_name": null,
"company_name": null,
"information": null,
"is_shared": true,
"created_at": 1583686067,
"updated_at": 1583686067,
"emails": [],
"phone_numbers": [
{
"id": 22266444,
"label": "Work",
"value": "+33134567899"
}
]
},
{
"id": 33333564,
"direct_link": "https://example.example",
"first_name": "Jessica",
"last_name": "Biel",
"company_name": "N-Sync",
"information": null,
"is_shared": true,
"created_at": 1583686086,
"updated_at": 1583686086,
"emails": [],
"phone_numbers": []
},
{
"id": 45678901,
"direct_link": "https://example.example",
"first_name": null,
"last_name": null,
"company_name": null,
"information": null,
"is_shared": true,
"created_at": 1583686105,
"updated_at": 1583686105,
"emails": [],
"phone_numbers": [
{
"id": 22266444,
"label": "Work",
"value": "+33134567333"
}
]
},
{
"id": 56789123,
"direct_link": "https://example.example",
"first_name": "Jacky",
"last_name": "Rowland",
"company_name": "Test Company1",
"information": "",
"is_shared": true,
"created_at": 1583745888,
"updated_at": 1608556499,
"emails": [
{
"id": 76594398,
"label": "Work",
"value": "mandatory_field#example.com"
}
],
"phone_numbers": [
{
"id": 60650277,
"label": "Mobile",
"value": "+33652556777"
}
]
}
],
"meta": {
"count": 6,
"total": 241,
"current_page": 1,
"per_page": 5,
"next_page_link": "https://example.example",
"previous_page_link": null
}
}
You could use something basic like this:
_.each(pm.response.json().contacts, (contact) => {
if(contact.last_name === "Rowland") {
pm.environment.set(`${contact.first_name}_${contact.last_name}_number`, contact.phone_numbers[0].value)
}
})
There are probably better and more performant ways to do this but if you just want to set a variable for that contact, no matter where they are in the response - This would work :D
you can use forEach or _.each as danny mentioned to get all numbers else use:
console.info(jsonData.contacts.find((a)=>a.first_name==="Jacky").phone_numbers[0].value)
use array.find to find the contact with first_name jacky adn then get phone_number[0].value from it.
if you want all numbers from that array then use:
console.info(jsonData.contacts.find((a)=>a.first_name==="Jacky").phone_numbers.map((a)=>a.value))
here we map the result to get only the numbers from phone_number array.
is it what you looking for !?

Search Similar value in json [duplicate]

This question already has answers here:
Find object by id in an array of JavaScript objects
(36 answers)
Closed 4 years ago.
when i am using fetch i am getting data in json format. I want to search json via cust_id and return only matching record. please tell me how to do it. I have to show all the credit card the person have.
"objects": [
{
"card_number": "123412341234",
"created_at": "2018-10-06T06:02:25.053942",
"cust_id": "12345",
"id": 1,
"resource_uri": "/api/card/1/",
"status": "completed"
},
{
"card_number": "213412345678",
"created_at": "2018-10-06T06:53:22.588967",
"cust_id": "12345",
"id": 3,
"resource_uri": "/api/card/3/",
"status": "pending"
},
]
var objects= [
{
"card_number": "123412341234",
"created_at": "2018-10-06T06:02:25.053942",
"cust_id": "12345",
"id": 1,
"resource_uri": "/api/card/1/",
"status": "completed"
},
{
"card_number": "213412345678",
"created_at": "2018-10-06T06:53:22.588967",
"cust_id": "12345",
"id": 3,
"resource_uri": "/api/card/3/",
"status": "pending"
},
{
"card_number": "213412345678",
"created_at": "2018-10-06T06:53:22.588967",
"cust_id": "12345",
"id": 3,
"resource_uri": "/api/card/3/",
"status": "pending"
},
]
console.log(objects.filter(i=>i['cust_id'] === '12345'))
I hope it helps
var val={
"objects": [
{
"card_number": "123412341234",
"created_at": "2018-10-06T06:02:25.053942",
"cust_id": "12345",
"id": 1,
"resource_uri": "/api/card/1/",
"status": "completed"
},
{
"card_number": "213412345678",
"created_at": "2018-10-06T06:53:22.588967",
"cust_id": "12345",
"id": 3,
"resource_uri": "/api/card/3/",
"status": "pending"
},
]
};
function get(val,custid){
var result;
for(var i=0;i<val.objects.length;i++){
if(val.objects[i].cust_id=custid){
result= val.objects[i];
}
}
return result;
}
console.log(get(val,"1235"));
For multiple records you can take result as array and use array.push to insert in result (function variable) and return the array in end

I want to sort some parameters but gives me [object object] or not undefined

"text": "Introducing the Twitter Certified Products Program:
"retweet_count": 121,
"in_reply_to_status_id_str": null,
"id": 240859602684612608,
"geo": null,
"retweeted": false,
"possibly_sensitive": false,
"in_reply_to_user_id": null,
"place": null,
"user": {
"profile_sidebar_fill_color": "DDEEF6",
"profile_sidebar_border_color": "C0DEED",
"profile_background_tile": false,
"name": "Twitter API",
"profile_image_url": "http://a0.twimg.com/profile_images/2284...
"created_at": "Wed May 23 06:01:13 +0000 2007",
"location": "San Francisco, CA",
"follow_request_sent": false,
"profile_link_color": "0084B4",
"is_translator": false,
"id_str": "6253282",
"entities": {
"url": {
"urls": [
{
"expanded_url": null,
"url": "",
"indices": [
0,
22
]
}
]
},
"description": {
"urls": [
]
}
},
jquery
success: function(data) {
var result = JSON.parse(data); $.each(result, function (i, val) {
document.write(val.text+" "+val.retweet_count+"
");
});
"text": "Introducing the Twitter Certified Products Program:
It should be:
"text": "Introducing the Twitter Certified Products Program:",
You are missing a " and a comma.

How to parse JSON files from text with node.js?

So I"m trying to parse out an html response into JSON for accessible objects.
This is my router
router.get('/yammer', function(req, res) {
var userFields;
var yammerCode = req.query.code;
var getYammerFieldsAddress = "http://www.yammer.combalwh;eoiahweg";
getYammerFieldsAddress += yammerCode;
console.log(getYammerFieldsAddress);
httpreq.get(getYammerFieldsAddress, function(err, response) {
if (err) return console.log(err);
console.log(response);
var yammerUserInfo = response.body;
var blah = yammerUserInfo.user;
console.log(blah);
But the info comes like this
{
"user":
{
"timezone": "Hawaii",
"interests": null,
"type": "user",
"mugshot_url": "https://www.yammer.com/yamage-backstage/photos/…",
"kids_names": null,
"settings": {
"xdr_proxy": "https://stagexdrproxy.yammer.com"
},
"schools": [],
"verified_admin": "false",
"birth_date": "",
"expertise": null,
"job_title": "",
"state": "active",
"contact": {
"phone_numbers": [],
"im": {
"provider": "",
"username": ""
},
"email_addresses": [
{
"type": "primary",
"address": "test#yammer-inc.com"
}
]
},
"location": null,
"previous_companies": [],
"hire_date": null,
"admin": "false",
"full_name": "TestAccount",
"network_id": 155465488,
"stats": {
"updates": 2,
"followers": 0,
"following": 0
},
"can_broadcast": "false",
"summary": null,
"external_urls": [],
"name": "clientappstest",
"network_domains": [
"yammer-inc.com"
],
"network_name": "Yammer",
"significant_other": null,
"id": 1014216,
"web_url": "https://www.yammer.com/yammer-inc.com/users/…",
"url": "https://www.yammer.com/api/v1/users/101416",
"guid": null
},
"access_token": {
"view_subscriptions": true,
"expires_at": null,
"authorized_at": "2011/04/06 16:25:46 +0000",
"modify_subscriptions": true,
"modify_messages": true,
"network_permalink": "yammer-inc.com",
"view_members": true,
"view_tags": true,
"network_id": 155465488,
"user_id": 1014216,
"view_groups": true,
"token": "ajsdfiasd7f6asdf8o",
"network_name": "Yammer",
"view_messages": true,
"created_at": "2011/04/06 16:25:46 +0000"
},
So it seems there are multiple objects coming through. I've tried accessing them from the response body, I've also tried JSON.stringify() and I can't access it. ANy ideas? Thanks!
Replace this line
var yammerUserInfo = response.body;
With
var yammerUserInfo = JSON.parse(response.body);
and it should work properly. :)
Try
var jsonObject = JSON.parse(response.body);

Categories