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);
Related
Issue:
I'm trying to update(axios.patch) active data from false to true of a nested object (children) by ID using axios patch request. I'm using vuejs as my frontend and json-server as my backend. Can anyone please help me.
Data:
{
"id": 3,
"icon": "store",
"name": "Store Management",
"children": [
{
"id": 1,
"name": "Tables",
"icon": "",
"active": false,
"path": "/store-management/tables"
},
{
"id": 2,
"name": "Discounts",
"icon": "",
"active": false,
"path": "/store-management/discounts"
},
{
"id": 3,
"name": "Surcharges",
"icon": "",
"active": false,
"path": "/store-management/surcharges"
},
{
"id": 4,
"name": "Promos",
"icon": "",
"active": false,
"path": "/store-management/promos"
}
],
"expanded": true,
"path": "",
"active": false,
"hasChildren": true
}
Function:
When I call the #click function the navigateChildren will execute and it needs to get the path of the nested object and at the same time update the active value to true or false.
async navigateChildren(id) {
try {
const menuChildren = await axios.get('http://localhost:3000/menu/3')
const menuChildrenList = menuChildren.data
const children = menuChildrenList.children[id - 1]
const inactive = await axios.patch(
'http://localhost:3000/menu/' + this.menuId,
{
active: false
}
)
console.log(inactive)
const active = await axios.patch('http://localhost:3000/menu/3', {
children: {
active: true
}
})
console.log(active)
const path = children.path
this.$store.commit('setMenuId', id)
this.$router.push(path)
console.log(children)
} catch (error) {
}
}
Many Thanks.
I have a JSON like this, how to get the value of StatusDescription? I tried many times but the result is undefined. Here is my JSON:
{
"meta": {
"a2": 200,
"ta": "dasd",
"asdd": "asdda"
},
"data": {
"items": [
{
"id": "",
"number": "",
"origin_info": {
"ItemReceived": "2021-10-02 02:07:49",
"phone": 123456789,
"trackinfo": [
{
"StatusDescription": "what i need",
"Details": "",
"substatus": "ok"
},
{
"StatusDescription": "what i need",
"Details": "",
"substatus": "ok"
}
]
},
"destination_info": null,
"lastEvent": "grgrgrgrgr",
"lastUpdateTime": "mewmemew"
}
]
}
}
I'm using in my NodeJS app, like myapp.js, and console.log()
Try this
I stored your sample json in variable json
var json = {
"meta": {
"a2": 200,
"ta": "dasd",
"asdd": "asdda"
},
"data": {
"items": [
{
"id": "",
"number": "",
"origin_info": {
"ItemReceived": "2021-10-02 02:07:49",
"phone": 123456789,
"trackinfo": [
{
"StatusDescription": "what i need",
"Details": "",
"substatus": "ok"
},
{
"StatusDescription": "what i need",
"Details": "",
"substatus": "ok"
}
]
},
"destination_info": null,
"lastEvent": "grgrgrgrgr",
"lastUpdateTime": "mewmemew"
}
]
}
}
Accessed it like below
console.log(json.data.items[0].origin_info.trackinfo[0].StatusDescription);
Items is an array and we took array element 0.
trackinfo again is an array and we took array element 0.
We can change array index or loop through and get required values.
You have to iterate through your items and trackinfo to get to StatusDescription. Try this one.
const data = {
"meta": {
"a2": 200,
"ta": "dasd",
"asdd": "asdda"
},
"data": {
"items": [
{
"id": "",
"number": "",
"origin_info": {
"ItemReceived": "2021-10-02 02:07:49",
"phone": 123456789,
"trackinfo": [
{
"StatusDescription": "what i need",
"Details": "",
"substatus": "ok"
},
{
"StatusDescription": "what i need",
"Details": "",
"substatus": "ok"
}
]
},
"destination_info": null,
"lastEvent": "grgrgrgrgr",
"lastUpdateTime": "mewmemew"
}
]
}
}
const items = data.data.items.map(item => item)
const trackinfo = items.map(item => item.origin_info.trackinfo).flat()
console.log(trackinfo)
const statusDescription = trackinfo.map(trackinfo => trackinfo.StatusDescription)
console.log(statusDescription)
Regardless of the JSON object structure (simple or complex) what would be the ideal method to extract all urls from the following object into an array to iterate over in Javascript?
{
"url": "https://example.com:443/-/media/images/site/info",
"data": [
{
"id": "da56fac6-6907-4055-96b8-f8427d4c64fd",
"title": "AAAA 2021",
"time": "",
"dateStart": "2021-03-01T08:00:00Z",
"dateEnd": "2021-12-31T15:00:00Z",
"address": "",
"geo": {
"longitude": "",
"latitude": "",
"mapExternalLink": ""
},
"price": "Free Admission",
"masonryImage": "https://example.com:443/-/media/images/site/siteimages/tcsm2021/fullwidthbanner/tcsmfullwidthicecream.ashx",
"image": "https://example.com:443/-/media/images/site/siteimages/tcsm2021/fullwidthbanner/tcsmfullwidthicecream.ashx",
"showDateInfo": false,
"showDateInfoOnListings": false,
"showTimeInfo": false,
"showTimeInfoOnListings": false,
"tags": [
{
"key": "Lifestyle",
"name": "Lifestyle"
}
],
"partnerName": "",
"sort_data": {
"recommended": 0,
"recent": 3,
"partner": 0,
"popular": 0
}
}
]
}
I would like to get the results in an array such as:
[
https://example.com:443/-/media/images/site/info,https://example.com:443/-/media/images/site/siteimages/tcsm2021/fullwidthbanner/tcsmfullwidthicecream.ashx, https://example.com:443/-/media/images/site/siteimages/tcsm2021/fullwidthbanner/tcsmfullwidthicecream.ashx
]
I gather that i would need to apply some regex to extract the urls but not sure how to treat the json object as string for regex processing?
I think the better and easier way is to stringfy given json into string and solve it by regex.
But still if you need to solve it by recursive, try the codes below:
const obj = {
url: "https://example.com:443/-/media/images/site/info",
data: [
{
id: "da56fac6-6907-4055-96b8-f8427d4c64fd",
title: "AAAA 2021",
time: "",
dateStart: "2021-03-01T08:00:00Z",
dateEnd: "2021-12-31T15:00:00Z",
address: "",
geo: {
longitude: "",
latitude: "",
mapExternalLink: "",
},
price: "Free Admission",
masonryImage:
"https://example.com:443/-/media/images/site/siteimages/tcsm2021/fullwidthbanner/tcsmfullwidthicecream.ashx",
image: "https://tw.yahoo.com",
showDateInfo: false,
showDateInfoOnListings: false,
showTimeInfo: false,
showTimeInfoOnListings: false,
tags: [
{
key: "Lifestyle",
name: "Lifestyle",
link: "https://www.google.com",
},
],
partnerName: "",
sort_data: {
recommended: 0,
recent: 3,
partner: 0,
popular: 0,
anotherObj: {
link: "https://www.github.com",
},
},
},
],
};
function getUrl(obj) {
const ary = [];
helper(obj, ary);
return ary;
}
function helper(item, ary) {
if (typeof item === "string" && isUrl(item)) {
ary.push(item);
return;
} else if (typeof item === "object") {
for (const k in item) {
helper(item[k], ary);
}
return;
}
return null;
}
function isUrl(str) {
if (typeof str !== "string") return false;
return /http|https/.test(str);
}
console.log(getUrl(obj));
But if you use this solution you need to transfer your json into js object
i'd agree to use a JSON parser, but if you want to do it with a regular expression, you might try this
console.log(JSON.stringify({
"url": "https://example.com:443/-/media/images/site/info",
"data": [{
"id": "da56fac6-6907-4055-96b8-f8427d4c64fd",
"title": "AAAA 2021",
"time": "",
"dateStart": "2021-03-01T08:00:00Z",
"dateEnd": "2021-12-31T15:00:00Z",
"address": "",
"geo": {
"longitude": "",
"latitude": "",
"mapExternalLink": ""
},
"price": "Free Admission",
"masonryImage": "https://example.com:443/-/media/images/site/siteimages/tcsm2021/fullwidthbanner/tcsmfullwidthicecream.ashx",
"image": "https://example.com:443/-/media/images/site/siteimages/tcsm2021/fullwidthbanner/tcsmfullwidthicecream.ashx",
"showDateInfo": false,
"showDateInfoOnListings": false,
"showTimeInfo": false,
"showTimeInfoOnListings": false,
"tags": [{
"key": "Lifestyle",
"name": "Lifestyle"
}],
"partnerName": "",
"sort_data": {
"recommended": 0,
"recent": 3,
"partner": 0,
"popular": 0
}
}]
}).match(/(?<=")https?:\/\/[^\"]+/g));
(?<=")https?:\/\/[^\"]+ basically finds patterns that start with a protocol scheme (http:// or https:// preceded by a " character) followed by anything that is not "
I Have an JSON response from an external API. Problem is i only know how to log the response but not manipulate it. In this case, I need to get some information from the response and loop through the entire response to show the list of all the users. Here is my code so far. Its not a good one, but this what i could do with my minimal javascript skills.
};
var response= UrlFetchApp.fetch(url, options)
var call= JSON.parse(response.getContentText());
var people=call.data;
var user= {}
user.ID = call.data[1].id;
user.Email = call.data[1].email;
user.Name= call.data[1].display_name;
Logger.log(user)
}
Sample response:
"data": [
{
"id":00126,
"first_name": "Test",
"last_name": "Test",
"archived": false,
"display_name": "Test Test",
"email": "test#test.com",
"termination_date": null,
"mobile_phone": null,
"office_phone": null,
"deleted_at": null,
"deleted": false,
},
"data": [
{
"id":00126,
"first_name": "Test",
"last_name": "Test",
"archived": false,
"display_name": "Test Test",
"email": "test#test.com",
"termination_date": null,
"mobile_phone": null,
"office_phone": null,
"deleted_at": null,
"deleted": false,
},
You can use Array.prototype.map to iterate through data and return required information only from the object
let data = [
{
"id": 00126,
"first_name": "Test",
"last_name": "Test",
"archived": false,
"display_name": "Test Test",
"email": "test#test.com",
"termination_date": null,
"mobile_phone": null,
"office_phone": null,
"deleted_at": null,
"deleted": false,
}]
let res = data.map(({id, email, display_name}) => ({ID: id, Email: email, Name: display_name}));
console.log(res)
If ES6 is not supported
var res = data.map(function(userData) {
return {ID: userData.id, Email: userData.email, Name: userData.display_name}
});
I am having some troubles with looping through a JSON structure through jQuery,
Here is my JSON data:
{
"suppliers": [
{
"Supplier": {
"id": "5704ebeb-e5e0-4779-aef4-16210a00020f",
"name": "Gillmans",
"mobile": "",
"office_telephone": "00000",
"ooh_contact": "00000",
"fax_number": "",
"address_line_1": "St Oswalds Road",
"address_line_2": "Gloucester",
"address_line_3": "",
"address_line_4": "",
"postcode": "GL1 2SG",
"email": "email#example.com",
"contact": "",
"position": "",
"aov": "180.00",
"engineer": false,
"cc_on_new_job_emails": true,
"can_add_quotes": false,
"notes": "",
"status": "1",
"created": "2016-04-06 11:58:51",
"modified": "2016-07-27 11:23:01",
"status_text": "Active",
"engineer_text": "No",
"cc_on_new_job_emails_text": "Yes"
},
"Trade": [],
"PostcodeArea": []
},
{
"Supplier": {
"id": "571e390f-91e8-4745-8f78-168b0a00020f",
"name": "Kings",
"mobile": "",
"office_telephone": "00000",
"ooh_contact": "0000",
"fax_number": "",
"address_line_1": "",
"address_line_2": "",
"address_line_3": "",
"address_line_4": "",
"postcode": "",
"email": "",
"contact": "",
"position": "Account Manager; Joanne Brook",
"aov": null,
"engineer": false,
"cc_on_new_job_emails": false,
"can_add_quotes": false,
"notes": "",
"status": "1",
"created": "2016-04-25 16:34:39",
"modified": "2016-07-08 15:22:15",
"status_text": "Active",
"engineer_text": "No",
"cc_on_new_job_emails_text": "No"
},
"Trade": [],
"PostcodeArea": []
}
]
}
This JSON is returned from my AJAX call in a variable called data. data is a Javascript object, i.e. it's already been parsed by the ajax call.
I am trying to loop through this JSON data and grab the name and id properties. Here is how I have done it:
$.each(data, function(k, v) {
$.each(this, function(key, val) {
$.each(this, function(key2, val2) {
$.each(this, function(key3, val3) {
if(key3 == 'name')
{
alert(val3);
}
});
});
});
});
This will print all of the name values but obviously this is quite a messy way and I was wondering if there is an easier way I can get the name and id properties of this structure and store them in variables?
You can deal with the JSON as an object if you parse it:
//this has already been done by the ajax call by the sounds of it.
//var jsObj = JSON.parse(data);
//suppliers is an array now ([]), so loop it
$.each(data.suppliers, function(index, value){
//value is a supplier object ({}) so you can acces it's properties directly
alert(value.Supplier.name);
});
$.each(data.suppliers, function(){
alert(this.Supplier.id);
});
Try this :
var data = {
"suppliers":[
{
"Supplier":{
"id":"5704ebeb-e5e0-4779-aef4-16210a00020f",
"name":"Gillmans"
},
"Trade":[
],
"PostcodeArea":[
]
},
{
"Supplier":{
"id":"571e390f-91e8-4745-8f78-168b0a00020f",
"name":"Kings"
},
"Trade":[
],
"PostcodeArea":[
]
}
]
}
$.each(data.suppliers, function(k, v) {
alert(this.Supplier.id);
})