How to get "source" from JSON object - javascript

I'm trying to build a custom Facebook page feed into my website. When the posts on the Facebook page have only images it works great, but when they have videos we've got a problem. What I would like to happen is a mini version of the video to be place as it was an image itself. However I'm a newbie to the graph api, because of that I don't know how to grab the "source" element of the posts that have video on them.
Here is how the JSON objetc looks like:
{
"name": "Patrick Oliveira",
"picture": {
"data": {
"is_silhouette": false,
"url": "https://fbcdn-profile-a.akamaihd.net/hprofile-ak-xft1/v/t1.0-1/c13.0.50.50/p50x50/11694800_709940652467661_5760283552162746065_n.jpg?oh=8ce289debf38df76b1a8ad72e9e32950&oe=5641D882&__gda__=1447414822_01484acd6dcdb29c62a7278a140bb592"
}
},
"posts": {
"data": [
{
"full_picture": "https://fbcdn-sphotos-a-a.akamaihd.net/hphotos-ak-xft1/v/t1.0-9/p417x417/11873451_734632043331855_4522184841179328970_n.jpg?oh=67bd84af22a94bc59a2996ff8fa0a8d8&oe=563F7BE8&__gda__=1447502842_a29144ab596e29d3d92d2239d376adc9",
"message": "Lan\u00e7ado em fevereiro de 1990, o Photoshop completa 25 anos como o programa de edi\u00e7\u00e3o de imagens mais famoso do mundo. Parab\u00e9ns Adobe!",
"created_time": "2015-08-14T20:52:08+0000",
"id": "213578595437205_734632043331855"
},
{
"full_picture": "https://scontent.xx.fbcdn.net/hphotos-xft1/v/t1.0-9/q81/s720x720/11415380_700706213391105_871834721491614634_n.jpg?oh=8672f7ae4931323baaf012e5f57a6079&oe=567F5D35",
"message": "\"Agora eu sei de que \u00e9 feito aquele ch\u00e3o\".\n-- cliente",
"created_time": "2015-07-04T20:05:01+0000",
"id": "213578595437205_700706213391105"
},
{
"full_picture": "https://fbcdn-sphotos-f-a.akamaihd.net/hphotos-ak-xpt1/v/t1.0-9/s720x720/11406889_700700410058352_5592320885219405365_n.jpg?oh=acedee420f8e4944201c714e30f70627&oe=5679534C&__gda__=1451225194_477268223eedc2217b2ae1dcdd345399",
"message": "Levante que hoje \u00e9 Sexta!",
"created_time": "2015-07-03T09:27:01+0000",
"id": "213578595437205_700700410058352"
},
{
"full_picture": "https://fbexternal-a.akamaihd.net/safe_image.php?d=AQBxQzu6zRD6fM_d&w=720&h=720&url=http\u00253A\u00252F\u00252Fi.ytimg.com\u00252Fvi\u00252F2K9eMZyD5jc\u00252Fmaxresdefault.jpg&cfs=1",
"message": "Ferramenta poderosa pra quem trabalha com fotos de arquitetura, o Adaptive Wide Angle pode ser um poderoso aliado!\nhttps://www.youtube.com/watch?v=2K9eMZyD5jc",
"created_time": "2015-07-02T18:25:01+0000",
"source": "http://www.youtube.com/v/2K9eMZyD5jc?version=3&autohide=1&autoplay=1",
"id": "213578595437205_700700186725041"
},
{
"full_picture": "https://fbcdn-sphotos-b-a.akamaihd.net/hphotos-ak-xft1/v/t1.0-9/s720x720/541646_700699430058450_5858057325981612930_n.jpg?oh=24a5d3e03cf1f782262e0b72d04831b4&oe=567999FA&__gda__=1451117341_93c352ddfa2804fa4047d84ab94978d9",
"message": "Come\u00e7ando o m\u00eas de Julho com o p\u00e9...",
"created_time": "2015-07-01T10:23:00+0000",
"id": "213578595437205_700699430058450"
}
],
"paging": {
"previous": "https://graph.facebook.com/v2.4/213578595437205/posts?limit=5&fields=full_picture,message,created_time,source&since=1439585528&access_token=1641569939420394|NyfBDunYwpFoZrtAoCSfqTV2-uU&__paging_token=enc_AdDQS8eEeKGQ3tvUJJxS1kyUXRwabHz2C1GZA0QZCufpZCHklYUI76WLCrigOB3IT1yxUtsCvx60ZA2haPnZA2Xoc2BOvPOLkM9eZBrbbrV1A87hVgIgZDZD&__previous=1",
"next": "https://graph.facebook.com/v2.4/213578595437205/posts?limit=5&fields=full_picture,message,created_time,source&access_token=1641569939420394|NyfBDunYwpFoZrtAoCSfqTV2-uU&until=1435746180&__paging_token=enc_AdAVBcOniyc1nbopw3Gr3CkmZB1pUDYBmZBghDmQXLunZBbvcuO1xttx6vpnkZBskAawu1sdcfh6qZCrU3sZA5MzZAkRQMT2VALYxOkCJOQZCm38ebDd2wZDZD"
}
},
"id": "213578595437205"
}
The fourth post is a video post, so I thought maybe I could generate a smaller video feed if I could grab that video source there.
Here is what I've been trying to do:
$.getJSON("https://graph.facebook.com/"+$page_id+"/?fields=name,picture,posts{full_picture,message,created_time}&access_token="+$access_token, function(fb) {
fb.posts.data[3].source;
});
However, the only thing I get from that is "undefined". If I do fb.posts.data[3].message or fb.posts.data[3].created_time or any of the other options it works, just for source that it returns "undefined". What am I doing wrong?

I found out what was wrong, so stupid. The request URL was missing the source element. So with this it works:
$.getJSON("https://graph.facebook.com/"+$page_id+"/?fields=name,picture,posts{full_picture,message,created_time,source}&access_token="+$access_token, function(fb) {
fb.posts.data[3].source;
});
I'm sorry for the mistake, it was my bad.

Related

How do you map an array of objects within an object?

I am trying to map an array of objects within an object and I can't seem to get it working. My code's goal is to map and then display the content within the "menu" array.
Here is the structure of the object (logged to console from a state).
Object {
"id": 1,
"img": "https://cuisinederue.org/wp-content/uploads/2019/08/Greg2.png",
"menu": Array [
Object {
"description": "Les prix sont défini à la tête du client",
"name": "Greg's Burger",
"price": 1,
},
Object {
"description": "Les prix sont défini à la tête du client",
"name": "Poutine double cheese bacon",
"price": 1,
},
Object {
"description": "Les prix sont défini à la tête du client",
"name": "Cône de poulet pop corn et frites maison",
"price": 1,
},
Object {
"description": "Les prix sont défini à la tête du client",
"name": "Grilled cheese Philly steak",
"price": 1,
},
Object {
"description": "Les prix sont défini à la tête du client",
"name": "Poutine Philly cheese steak",
"price": 1,
},
Object {
"description": "Les prix sont défini à la tête du client",
"name": "Boulette de mac'n'cheese",
"price": 1,
},
],
"name": "Greg's dinner",
"type": "SOUTHERN COMFORT",
}
And here is the code that I'm trying to get to work: (specifically the details.menu.map part)
const Details = ({navigation, idTruck}) =>{
const [details, setDetails] = useState([]);
const [detailsDone, setDetailsDone] = useState(false);
const getDetails = () => {
fetch("https://foodtrack-420kbc-lg.herokuapp.com/trucks/1").then(res => res.json()).then(resp => setDetails(resp));
}
if(!detailsDone)
{
getDetails();
setDetailsDone(true);
}
console.log(details);
return (
<View style={styles.container}>
<Header title='Details'></Header>
<Image name="logo" style={styles.detailsImage} source={{uri: details.img}}></Image>
<Text name="nom">{details.name}</Text>
<Text name="style">{details.type}</Text>
{
details.menu.map(({description, name, price}) =>
<View style={styles.container}>
<Text name="nom">{name}</Text>
<Text name="prix">{price}</Text>
<Text name="desc">{description}</Text>
</View>
)
}
</View>
)
}
The error I am getting is: TypeError: undefined is not an object (evaluating 'details.menu.map'
Any help is greatly appreciated!
You have big problem in controlling JS asynchronous. Please try to understand it first before you start to study reactJS. Some async functions: setTimeout, setInterval, Ajax (call api), here is small tut . From this point, you don't need to use detailsDone state.
High performance when use useEffect for calling api only 1 time.
const initValue = {
id: 0,
name: "",
type: "",
img: "",
menu: []
}
const [details, setDetails] = useState(initValue); // init value is object, not array
React.useEffect(() => {
fetch("https://foodtrack-420kbc-lg.herokuapp.com/trucks/1")
.then(res => res.json())
.then(resp => setDetails(resp));
}, []); // ensure call api run 1 time when this component render.
it looks like you're trying to map over details.menu, but when the component loads initially, details is an empty array, which does not have property menu.
One workaround would be to conditionally render something else (like a loading indicator) until the data is set into component state.

How can I retrieve a index of text inside json

I need to retrieved a index inside a JSON data.
My query -> I want to get the position of the URL who contains the text "eisf" inside all the URL's.
I tried the function findIndex, but not working...
[{
"title": "CAP Pâtissier à La Ciotat - GRETA Marseille Méditerranée - Académie ...",
"url": "https://www.gretanet.com/formation-cap-patissier+la-ciotat+1007.html",
"displayedUrl": "https://www.gretanet.com/formation-cap-patissier+la-ciotat+1007.html",
"description": "Formation CAP Pâtissier à La Ciotat - GRETA Marseille Méditerranée - Académie d'Aix-Marseille.",
"siteLinks": []
},
{
"title": "Les sujets du CAP pâtissier - EISF",
"url": "https://www.eisf.fr/sujets-examen-cap-patisserie/",
"displayedUrl": "https://www.eisf.fr/sujets-examen-cap-patisserie/",
"description": "8 déc. 2018 - Vous voulez vous entrainer à l'examen du CAP Pâtissier ? Retrouver les annales des années précédentes. Sujets CAP Pâtissier 2018.",
"siteLinks": []
}]
You can iterate the array using forEach and check if url have that text using indexOf. It if is greater that -1 then push it to the indexArr
let data = [{
"title": "CAP Pâtissier à La Ciotat - GRETA Marseille Méditerranée - Académie ...",
"url": "https://www.gretanet.com/formation-cap-patissier+la-ciotat+1007.html",
"displayedUrl": "https://www.gretanet.com/formation-cap-patissier+la-ciotat+1007.html",
"description": "Formation CAP Pâtissier à La Ciotat - GRETA Marseille Méditerranée - Académie d'Aix-Marseille.",
"siteLinks": []
},
{
"title": "Les sujets du CAP pâtissier - EISF",
"url": "https://www.eisf.fr/sujets-examen-cap-patisserie/",
"displayedUrl": "https://www.eisf.fr/sujets-examen-cap-patisserie/",
"description": "8 déc. 2018 - Vous voulez vous entrainer à l'examen du CAP Pâtissier ? Retrouver les annales des années précédentes. Sujets CAP Pâtissier 2018.",
"siteLinks": []
}
];
let indexArr = [];
data.forEach(function(item, index) {
if (item.url.indexOf('eisf') !== -1) {
indexArr.push(index);
}
});
console.log(indexArr)

PHP Simple HTML DOM Parser for JavaScript Code Within the Page

I'm using PHP Simple DOM Parser, the HTML part is working as expected, but some of the content of the web page is shown with JavaScript. The JavaScript is within the HTML page not a separate file and the information I need is clear, in plain text.
This is how the JavaScript code starts, the information needed is in the end (location):
<script id="state">
window.__INITIAL_STATE__ = {
"detail": {
"listingTopNavigation": {},
"isTracked": false,
"id": 30279925,
"isImported": false,
"isErotic": false,
"isMessengerEnabled": false,
"categories": [{
"name": "Musique - Instruments",
"id": 23,
"isErotic": false
}, {
"name": "Guitares & Accessoires",
"id": 697,
"isErotic": false
}, {
"name": "Electrique",
"id": 2354,
"isErotic": false
}],
"imageData": {
"baseUrl": "https:\u002F\u002Fcan01.anibis.ch\u002FElectrique-Line-6-DL-4-Delay-Modeler",
"images": ["\u002F?[size]\u002Fanibis\u002F925\u002F279\u002F030\u002FLSmd7oN9LU6lAP5EbJQXXg_1.jpg", "\u002F?[size]\u002Fanibis\u002F925\u002F279\u002F030\u002Fhn2lNMOudUmuZofpM7wrsg_1.jpg", "\u002F?[size]\u002Fanibis\u002F925\u002F279\u002F030\u002FJKBbte21vEaD7ZJqcMi_Qg_1.jpg"]
},
"title": "Line 6 DL 4 Delay Modeler",
"description": "\u003Cp\u003EVerkaufe mein Delay DL 6 in absolut neuwertigem Zustand wegen Nichtgebrauch. Das Delay habe ich im Dezember 2018 neu bei Musix gekauft und verfügt über eine tolle Auswahl an Delay Effekten, welche auf Fender Gibson Marshall oder Vox in Extraklasse daherkommen. Das Gerät ist optisch und technisch absolut neuwertig, kommt in Originalverpackung und mit dem passenden Netzadapter von Line 6. \u003C\u002Fp\u003E\n",
"price": 190,
"offerType": "Offer",
"formattedPrice": "CHF 190.–",
"formattedModified": "19.08.2019",
"details": [{
"name": "Remise",
"value": "Retrait et envoi "
}, {
"name": "Type d’annonce",
"value": "Offre"
}],
"location": {
"country": "Suisse",
"state": "Soleure",
"zipCity": "4625 Oberbuchsiten (SO)"
},
How can I get these values in PHP variables to use after.
$country = $html->find(...);
$state = $html->find(...);
$zip_city = $html->find(...);
Thanks.
if ($html) {
if ($html->find('script[id=state]', 0)) {
$script = $html->find('script[id=state]', 0);
$script = ltrim($script, '<script id="state">window.__INITIAL_STATE__=');
$script = rtrim($script, '</script>');
$obj = json_decode($script, true);
if (isset($obj['detail']['contact']['phone'])) {
$tel = $obj['detail']['contact']['phone'];
$tel = ltrim($tel, '+41 ');
if (isset($obj['detail']['location']['street']))
$address = trim($obj['detail']['location']['street']);
if (isset($obj['detail']['location']['zipCity']))
$npa_ville = trim($obj['detail']['location']['zipCity']);
$npa_ville = explode(' ', $npa_ville, 2);
$npa = preg_replace('/[^0-9]/', '', $npa_ville[0]);
$ville = $npa_ville[1];

Rollup returns undefined or array with value when using map

I'm currently working with a rather large dataset so I'm looking to make the data variable smaller by nesting the data in a new variable 'nested_data'.
This is the data I'm using:
Landen,"Perioden","SITC","Onderwerpen_1","Waarde eenheid","Waarde"
Afghanistan,"2012","0 Voeding en levende dieren","Invoerwaarde","mln euro","1"
Afghanistan,"2012","1 Dranken en tabak","Invoerwaarde","mln euro","0"
Afghanistan,"2012","2 Grondstoffen niet eetbaar behalve...","Invoerwaarde","mln euro","."
Afghanistan,"2012","3 Minerale brandstoffen smeermiddele...","Invoerwaarde","mln euro","."
Afghanistan,"2012","4 Dierlijke en plantaardige oliën en ...","Invoerwaarde","mln euro","."
Afghanistan,"2012","5 Chemische producten","Invoerwaarde","mln euro","0"
Afghanistan,"2012","6 Fabricaten hoofdzakelijk gerangschi...","Invoerwaarde","mln euro","0"
Afghanistan,"2012","7 Machines en vervoermaterieel","Invoerwaarde","mln euro","1"
Afghanistan,"2012","8 Diverse gefabriceerde goederen","Invoerwaarde","mln euro","1"
Afghanistan,"2012","9 Niet afzonderlijk genoemde goederen","Invoerwaarde","mln euro","0"
I want this to be the result of the rollup:
[
{
"key": "0 Voeding en levende dieren",
"value": 1
},
{
"key": "1 Dranken en tabak",
"value": 0
},
{
"key": "2 Grondstoffen niet eetbaar behalve...",
"value": 7
},
{
"key": "3 Minerale brandstoffen smeermiddele...",
"value": 1
},
{
"key": "4 Dierlijke en plantaardige oliën en ...",
"value": 9
},
{
"key": "5 Chemische producten",
"value": 4
},
{
"key": "6 Fabricaten hoofdzakelijk gerangschi...",
"value": 12
},
{
"key": "7 Machines en vervoermaterieel",
"value": 3
},
{
"key": "8 Diverse gefabriceerde goederen",
"value": 0
},
{
"key": "9 Niet afzonderlijk genoemde goederen",
"value": 13
}
]
I've tried using d3 rollup like this:
.rollup(function(d){
return d.Waarde;
})
This has the following result:
My second attempt was using 'map', as follows:
.rollup(function(value){
return value.map(function(d){
return d.Waarde;
})
})
I liked that result much better but it's still not what I'm looking for:
While this method does add the correct value to the object, it puts it into an array (which 'map' obviously does). However I would like it to not place the value into an array but simply as the value of the key.
In your rollup method, that first argument...
.rollup(function(d){
return d.Waarde;
})
...is not an object: it's an array instead. Therefore, you almost got it right when you used map...
.rollup(function(value){
return value.map(function(d){
return d.Waarde;
})
})
...but the problem is that map will return an array, and that's not what you want. You want a sum:
.rollup(function(d) {
return d3.sum(d, function(e) {
return e.Waarde
});
})
Here is a demo with some changes in your data (you have "." as the value in some rows, which makes little sense here):
const csv = `Landen,"Perioden","SITC","Onderwerpen_1","Waarde eenheid","Waarde"
Afghanistan,"2012","0 Voeding en levende dieren","Invoerwaarde","mln euro","1"
Afghanistan,"2012","1 Dranken en tabak","Invoerwaarde","mln euro","0"
Afghanistan,"2012","2 Grondstoffen niet eetbaar behalve...","Invoerwaarde","mln euro","4"
Afghanistan,"2012","3 Minerale brandstoffen smeermiddele...","Invoerwaarde","mln euro","2"
Afghanistan,"2012","4 Dierlijke en plantaardige oliën en ...","Invoerwaarde","mln euro","7"
Afghanistan,"2012","5 Chemische producten","Invoerwaarde","mln euro","0"
Afghanistan,"2012","6 Fabricaten hoofdzakelijk gerangschi...","Invoerwaarde","mln euro","0"
Afghanistan,"2012","7 Machines en vervoermaterieel","Invoerwaarde","mln euro","1"
Afghanistan,"2012","8 Diverse gefabriceerde goederen","Invoerwaarde","mln euro","1"
Afghanistan,"2012","9 Niet afzonderlijk genoemde goederen","Invoerwaarde","mln euro","0"
Afghanistan,"2012","9 Niet afzonderlijk genoemde goederen","Invoerwaarde","mln euro","5"
Afghanistan,"2012","9 Niet afzonderlijk genoemde goederen","Invoerwaarde","mln euro","2"
Afghanistan,"2012","9 Niet afzonderlijk genoemde goederen","Invoerwaarde","mln euro","9"`;
const data = d3.csvParse(csv, d3.autoType);
const nest = d3.nest()
.key(function(d) {
return d.SITC
})
.rollup(function(d) {
return d3.sum(d, function(e) {
return e.Waarde
});
})
.entries(data)
console.log(nest)
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>

Tabs from json nodes

[
{
"idn" : "liquido",
"categoria": "Aromatizante Ambiental Liquido",
"productos": [
{
"nombre": "Canela"
},
{
"nombre": "Chanel"
},
{
"nombre": "Citrus"
},
{
"nombre": "Coco"
},
{
"nombre": "Floral"
},
{
"nombre": "Manzanas"
},
{
"nombre": "Spa Relax"
},
{
"nombre": "Vainilla"
}
]
},
{
"idn" : "aerosol",
"categoria": "Aromatizante Ambiental en Aerosol",
"productos": [
{
"nombre": "Good Sense Jardin de Tuscan Neutralizador de Olores Aerosol"
},
{
"nombre": "Good Sense Potpourri Neutralizador de Olores Aerosol"
},
{
"nombre": "Good Sense No Smoke Eliminador de Olores Aerosol"
}
]
}
]
I have this code, from a json file, i make a function, to make tabs, for each "categoria", but when i try a make "click" to the "li" element, doesn't work, it's like not make a click, but the html is generating correctly.
Even if add a "a" element,this not work. But
Any one, knows why?. Thanks
You did not show your client-side code. It is a problem with client-side code. Also you did not even said which language you use. Please provide more information. Please check json.org before you ask a question. Good Luck :)

Categories

Resources