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);
})
Related
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 need to render some images from some json that I am being given. The code looks like
class App extends React.Component {
componentDidMount() {
$.get(
"url"
data => {
});
}
render() {
return React.createElement("div", null, "hello");
}}
ReactDOM.render(React.createElement(App, null), document.body);
"url" is the json that I have passed in (but I do not want to make it public). It looks similar to this:
{
"total_count": null,
"_links": {
"self": {
"href": ""
},
"next": {
"href": ""
}
},
"_embedded": {
"showorks": [{
"id": "",
"slug": "",
"created_at": "",
"updated_at": "",
"title": "",
"category": "",
"medium": ",
"date": "",
"dimensions": {
"in": {
"text": "",
"height": 70.9,
"width": 70.9,
"depth": null,
"diameter": null
},
"cm": {
"text": "180.1 × 180.1 cm",
"height": 180.1,
"width": 180.1,
"depth": null,
"diameter": null
}
},
"published": true,
"website": "",
"signature": "",
"series": null,
"prov": "",
"lit": "",
"hist": "",
"isst": "",
"additional_information": "",
"image_rights": "",
"blurb": "",
"unique": false,
"maker": null,
"icon": ,
"inquire": false,
"acquire": false,
"share": true,
"message": null,
"sell":,
"image_versions": ,
"_links": {
"thumbnail": {
"href": ""
},
"image": {
"href": "",
"templated": true
},
"partner": {
"href": ""
},
"self": {
"href": ""
},
"link": {
"href": ""
},
"genes": {
"href": ""
},
"rar": {
"href": ""
},
"cim": {
"href": ""
},
"coll": {
"href": ""
}
},
"_embedded": {
"editions": []
}
}, {
"id": "",
I need the thumbnail for each id but I'm not sure how to iterate through the json to pull out each thumbnail in react/javascript
First, I totally recommend you to use JSX syntax to use React better. To do that, you will need a few Javascript Array helper function and some methods.
As you can see below:
class App extends React.Component
{
componentDidMount()
{
// We could imagine the incoming JSON data
// const exampleJson =
// {
// elements:
// [
// { href: 'example1', text: 'link value', style: { height: '10px' } },
// ],
// };
// This fetch API will help you to get JSON from URL like JQuery $.get
const exampleJson = fetch('http://example.com/links.json')
.then(function(response)
{
return response.json(); // get the values of JSON as string type
})
.then(function(myJson)
{
return JSON.stringify(myJson); // convert the JSON data to javascript object
});
this.setState(exampleJson); // it's like this.setState({ elements: [array values] });
console.log(exampleJson); // to do debug of your JSON data
}
render()
{
// we getting the elements array from state object
// with object spread operator
const { elements } = this.state;
// get values all of your json array
// loop values to do React element
// return all new values to use loopAndSaveElements variable
const loopAndSaveElements = elements
.map(({ text, ...otherProps}) => React.createElement('a', otherItems, text));
// send return div of React as loopAndSaveElements as array children
return React.createElement("div", null, loopAndSaveElements);
}
}
By the way, i didn't run the snippet of example. But i hope it give you an information.
ES6+ Sources:
const
Array map
spread syntax
JSX syntax
fetch API
Can anyone help me to fetch the comments value from the below json structure.
Actually i want the id(very first column after items) for which the no of comments is 0. I m able to read the id but unable to put the if condition (comment =0) return {id}
"data": {
"posts": {
"items": [
{
"id": ,
"content": {
"id": ,
"files": [],
"user_details": {
"firstname": "",
"lastname": ""
},
"comments": "",
"tags": [
"anonymous"
],
"likeCount": 0,
"group_details": {
"group_name": "",
"guid":
},
"propertytags": {
"empty": ""
},
"permalink": {
"link":
},
"isFollowed": ,
"followerCount": "",
"favorite": "",
"isLiked": ""
},
"contentType": "",
"group_details": {
"group_name": ,
"guid":
}
}
How to read comments value?????
data.posts.items[index].content.comments will give you the value of comments.
However to fetch the id based on comment value, you may use Array.filter() function.
let result = data.posts.items.filter(item => {
if (item.content.comments === "0") {
return item.id;
}
});
result will be an array of id for which the comments is 0.
Here is an example with the data you've shared JS Bin
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);