How to get image url - javascript

If I parse a Tweet from the Twitter API using:
tweet.entities.media
I get the below json. But how would I access media_url property? Its nested in a really difficult place inside the json object.
tweet.entities.media[0].media_url
returns an error.
{
"image": [
{
"id": 511403875438301200,
"id_str": "511403875438301185",
"indices": [
44,
66
],
"media_url": "http://some_url.jpg",
"media_url_https" : "https: //some_url.jpg",
"url": "http://whatever.com",
"display_url": "pic.twitter.com/BNIPh3ZlRD",
"expanded_url": "https://twitter.com/some_url/1",
"type": "photo",
"sizes": {
"thumb": {
"w": 150,
"h": 150,
"resize": "crop"
},
"small": {
"w": 680,
"h": 482,
"resize": "fit"
},
"large": {
"w": 2048,
"h": 1453,
"resize": "fit"
},
"medium": {
"w": 1200,
"h": 851,
"resize": "fit"
}
}
}
]
}

how would I access media_url?
It appears to me that you are just missing image[0]:
tweet.entities.media.image[0].media_url
$(document).ready(function() {
var tweet = jQuery.parseJSON( '{"entities":{"media":{"image":[{"id":511403875438301200,"id_str":"511403875438301185","indices":[44,66],"media_url":"http://pbs.twimg.com/media/BxjfHXxCEAETmig.jpg","media_url_https":"https: //pbs.twimg.com/media/BxjfHXxCEAETmig.jpg","url":"http://whatever.com","display_url":"pic.twitter.com/BNIPh3ZlRD","expanded_url":"https://twitter.com/AWish4Me/status/511403876642463744/photo/1","type":"photo","sizes":{"thumb":{"w":150,"h":150,"resize":"crop"},"small":{"w":680,"h":482,"resize":"fit"},"large":{"w":2048,"h":1453,"resize":"fit"},"medium":{"w":1200,"h":851,"resize":"fit"}}}]}}}');
document.body.innerHTML = tweet.entities.media.image[0].media_url;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

I think I got it.
It was breaking because some of the Tweets didn't have images..
I had to check for empty properties...
return {"image_url":(tweet.entities.media!==undefined)?((tweet.entities.media[0]!=="")?(tweet.entities.media[0].media_url):('')): ('') };

Related

I'd like to filter out objects which do not have an ext key on them

How can I remove objects which do not have an ext key? I want to take pictures, but there is a problem because some objects do not have a picture. I'm confused about filtering. Can it be done with reduce or filter?
{
"posts": [
{
"filename": "1647706792183",
"ext": ".png",
"w": 300,
"h": 450,
"tn_w": 166,
"tn_h": 250,
"tim": 1664328637690788,
"time": 1664328637,
"md5": "Omk9VtmPOD1U38U1OOAP/w==",
"fsize": 200271,
"resto": 0,
"country": "DK",
"bumplimit": 0,
"imagelimit": 0,
"semantic_url": "f1-relentless-formula-one-general-all-smiles",
"replies": 378,
"images": 155,
"unique_ips": 102,
"tail_size": 50
},
{
"now": "09/27/22(Tue)21:31:17",
"name": "Anonymous",
"resto": 123946553,
}
]
}
You can use .filter to run a function that returns true/false for each item of your data.
const data = { posts: [ .... ] };
const postsWithExt = data.posts.filter(post => post.ext !== undefined);
If you want to filter falsy values for .ext then use
posts.filter(post => !post.ext)
You can just filter your posts array where the ext property exists.
e.g.
const data = {
"posts": [{
"filename": "1647706792183",
"ext": ".png",
"w": 300,
"h": 450,
"tn_w": 166,
"tn_h": 250,
"tim": 1664328637690788,
"time": 1664328637,
"md5": "Omk9VtmPOD1U38U1OOAP/w==",
"fsize": 200271,
"resto": 0,
"country": "DK",
"bumplimit": 0,
"imagelimit": 0,
"semantic_url": "f1-relentless-formula-one-general-all-smiles",
"replies": 378,
"images": 155,
"unique_ips": 102,
"tail_size": 50
},
{
"now": "09/27/22(Tue)21:31:17",
"name": "Anonymous",
"resto": 123946553,
}
]
};
const result = data.posts.filter(x => x.ext);
console.log(result);

Read JSON, return the new (or deleted) object

So far, I've been successfully using Ruby to read and write JSON using the json gem, and now I want to level up the powers of my tools.
The JSON is served on a read-only server, and is returned as:
[{
"class_name": "User",
"id": "12",
"username": "Miranda",
"profile_image_urls": [{
"url": "12_128x128.jpg",
"width": 128,
"height": 128
}, {
"url": "12_200x200.jpg",
"width": 200,
"height": 200
}, {
"url": "12_400x400.jpg",
"width": 400,
"height": 400
}
]
}, {
"class_name": "User",
"id": "13",
"username": "Elin",
"profile_image_urls": [{
"url": "13_128x128.jpg",
"width": 128,
"height": 128
}, {
"url": "13_200x200.jpg",
"width": 200,
"height": 200
}, {
"url": "13_400x400.jpg",
"width": 400,
"height": 400
}
]
}, {
"class_name": "User",
"id": "14",
"username": "Joe",
"profile_image_urls": [{
"url": "14_128x128.jpg",
"width": 128,
"height": 128
}, {
"url": "14_200x200.jpg",
"width": 200,
"height": 200
}, {
"url": "14_400x400.jpg",
"width": 400,
"height": 400
}
]
}
]
Now, how can I process just the new object(s) if the next pull from the server has new objects?
example:
[
{
"class_name": "User",
"id": "15",
"username": "Ellie",
"profile_image_urls": [{
"url": "15_128x128.jpg",
"width": 128,
"height": 128
}, {
"url": "15_200x200.jpg",
"width": 200,
"height": 200
}, {
"url": "15_400x400.jpg",
"width": 400,
"height": 400
}
]
}, {
"class_name": "User",
"id": "12",
"username": "Miranda",
"profile_image_urls": [{
"url": "12_128x128.jpg",
"width": 128,
"height": 128
}, {
"url": "12_200x200.jpg",
"width": 200,
"height": 200
}, {
"url": "12_400x400.jpg",
"width": 400,
"height": 400
}
]
}, {
"class_name": "User",
"id": "13",
"username": "Elin",
"profile_image_urls": [{
"url": "13_128x128.jpg",
"width": 128,
"height": 128
}, {
"url": "13_200x200.jpg",
"width": 200,
"height": 200
}, {
"url": "13_400x400.jpg",
"width": 400,
"height": 400
}
]
}, {
"class_name": "User",
"id": "14",
"username": "Joe",
"profile_image_urls": [{
"url": "14_128x128.jpg",
"width": 128,
"height": 128
}, {
"url": "14_200x200.jpg",
"width": 200,
"height": 200
}, {
"url": "14_400x400.jpg",
"width": 400,
"height": 400
}
]
}
]
This should return the entire object for id 15
The solution that fits could:
use Ruby OR dependency-free javascript
Save the JSON to a file, and watch/read for changes locally
Read the JSON from the server directly and juggle the JSON in memory (the script my not be running all the time. The solution needs to be aware so it doesn't miss changes)
Assuming id is a key which necessarily uniquely identifies each of these objects…
It suffices to just remember the set of IDs you've so far handled, and filter the input such that you exclude those.
// this is the set of IDs you've so far handled.
// yes we're just using a regular JS object, since we can agree to use it moreorless like a HashSet.
// you can of course load this in from a file (for example if you saved your progress beforehand)
var handledIDs = {
"15": true
};
function handleServerOutput(payload) {
// payload should be in the exact format of your `example` snippet (i.e. a JSON array of objs).
var objsNeverBeforeHandled = payload.filter(function(obj) {
// true if that key maps to a true in the `handledIDs` dictionary
var hasBeenHandled = handledIDs[obj.id];
// exclude from the filtered payload any object that has been handled
return !hasBeenHandled;
});
// now you can iterate through the `objsNeverBeforeHandled`
objsNeverBeforeHandled.forEach(function(obj) {
// do whatever you like with obj
// …
// also remember to add it to the set of IDs you've handled
handledIDs[obj.id] = true;
});
// and you have the opportunity to save `handledIDs` somewhere for the next time you need to run this thing.
}

JSON.parse() works from console but not from function/code

Why parsing string into JSON (previously created with JSON.stringify()) works from console but from function it gives enigmatic error?
console.log(output); // in console i copy it into JSON.parse() and it works
output = JSON.parse(output); // Uncaught SyntaxError: Unexpected token index:1
My JSON:
{"type":"a","items":[{"id":"767758","id1":"1384882","id2":"1413749","c":"rgba(0, 100, 0, 5)","ls":"dashed","type":"l","d":{"t":"r","type":"1","hist":true},"w":5,"off":0},{"id":"6493942","id1":"1384882","id2":"5467332","c":"rgba(105, 105, 105, 5)","ls":"1","type":"l","d":{"t":"r","type":"h","hist":false},"w":5,"off":0},{"id":"1384882","id":"6c409d02-d937-11e4-a891-53b449010d08","d":{"t":"p","age":41,"xxx":5},"type":"n","t":"123","u":"p.png","g":[{"c":"rgb(255, 255, 255)","p":"ne","t":"5","fc":"rgb(0, 0, 0 )","w":false}],"x":-20.876105573962775,"y":41.26542299248838},{"id":"1413749","id":"e7e70a00-d3e4-11e4-b3ef-53b449010d08","d":{"t":"c","active":true,"r":47},"type":"n","t":"zxc","u":"p.png","g":[{"c":"#ccff99","p":"ne","t":"42","fc":"rgb(0, 0, 0)","w":5},{"c":"rgb(0, 0, 255)","p":"nw","fc":"rgb(0, 0, 0)"}],"x":149.06285284387724,"y":5.308329729351229},{"id":"5467332","id":"8f0f5c30-d3d9-11e4-b3ef-53b449010d08","d":{"t":"c","active":true,"r":47},"type":"n","t":"asd","u":"p.png","g":[{"c":"#ccff99","p":"ne","t":"","fc":"rgb(0, 0, 0)","w":false},{"p":"nw","fc":"rgb(0, 0, 0)"}],"x":-164.24347467678655,"y":-32.64876353378594}],"combos":{"iop":[],"dfg":[]},"jk":{"width":966,"height":890,"zoom":5,"offsetX":905,"offsetY":744}}
My code, there's something missing as others gave working JSfiddles:
var memory = '';
$buttonSave.click(function (event) {
if (helpers.isNUE(chart)) { return; }
var data = chart.serialize();
data = JSON.stringify(data).split(''); // string to array
data.forEach(function (datum) { // foreach character
memory += datum.charCodeAt(0).toString(2) + '2'; // get binary charcode, add padding "2"
});
console.info('memory saved: ' + memory);
event.preventDefault();
return false;
});
$buttonLoad.click(function (event) {
var data = memory.split('2'), // get binary code for each character
output = '',
serializedChart = {};
data.forEach(function (datum) {
output += String.fromCharCode(parseInt(datum, 2)); // read binary charcode and get character from it
});
console.warn('load done:');
try {
serializedChart = JSON.parse(output);
} catch (e) {
console.warn(e);
}
});
You are missing a final } from your json string. use this:
{
"type": "a",
"items": [
{
"id": "767758",
"id1": "1384882",
"id2": "1413749",
"c": "rgba(0, 100, 0, 5)",
"ls": "dashed",
"type": "l",
"d": {
"t": "r",
"type": "1",
"hist": true
},
"w": 5,
"off": 0
},
{
"id": "6493942",
"id1": "1384882",
"id2": "5467332",
"c": "rgba(105, 105, 105, 5)",
"ls": "1",
"type": "l",
"d": {
"t": "r",
"type": "h",
"hist": false
},
"w": 5,
"off": 0
},
{
"id": "6c409d02-d937-11e4-a891-53b449010d08",
"d": {
"t": "p",
"age": 41,
"xxx": 5
},
"type": "n",
"t": "123",
"u": "p.png",
"g": [
{
"c": "rgb(255, 255, 255)",
"p": "ne",
"t": "5",
"fc": "rgb(0, 0, 0 )",
"w": false
}
],
"x": -20.876105573962775,
"y": 41.26542299248838
},
{
"id": "e7e70a00-d3e4-11e4-b3ef-53b449010d08",
"d": {
"t": "c",
"active": true,
"r": 47
},
"type": "n",
"t": "zxc",
"u": "p.png",
"g": [
{
"c": "#ccff99",
"p": "ne",
"t": "42",
"fc": "rgb(0, 0, 0)",
"w": 5
},
{
"c": "rgb(0, 0, 255)",
"p": "nw",
"fc": "rgb(0, 0, 0)"
}
],
"x": 149.06285284387724,
"y": 5.308329729351229
},
{
"id": "8f0f5c30-d3d9-11e4-b3ef-53b449010d08",
"d": {
"t": "c",
"active": true,
"r": 47
},
"type": "n",
"t": "asd",
"u": "p.png",
"g": [
{
"c": "#ccff99",
"p": "ne",
"t": "",
"fc": "rgb(0, 0, 0)",
"w": false
},
{
"p": "nw",
"fc": "rgb(0, 0, 0)"
}
],
"x": -164.24347467678655,
"y": -32.64876353378594
}
],
"combos": {
"iop": [],
"dfg": []
},
"jk": {
"width": 966,
"height": 890,
"zoom": 5,
"offsetX": 905,
"offsetY": 744
}
}
Is output already parsed? If so, it looks like you're trying to parse output twice, if the output is already a JSON value, you do not need to parse it again.
You're missing an } at the end of your JSON. If you add that it should work.
{"type":"a","items":[{"id":"767758","id1":"1384882","id2":"1413749","c":"rgba(0, 100, 0, 5)","ls":"dashed","type":"l","d":{"t":"r","type":"1","hist":true},"w":5,"off":0},{"id":"6493942","id1":"1384882","id2":"5467332","c":"rgba(105, 105, 105, 5)","ls":"1","type":"l","d":{"t":"r","type":"h","hist":false},"w":5,"off":0},{"id":"1384882","id":"6c409d02-d937-11e4-a891-53b449010d08","d":{"t":"p","age":41,"xxx":5},"type":"n","t":"123","u":"p.png","g":[{"c":"rgb(255, 255, 255)","p":"ne","t":"5","fc":"rgb(0, 0, 0 )","w":false}],"x":-20.876105573962775,"y":41.26542299248838},{"id":"1413749","id":"e7e70a00-d3e4-11e4-b3ef-53b449010d08","d":{"t":"c","active":true,"r":47},"type":"n","t":"zxc","u":"p.png","g":[{"c":"#ccff99","p":"ne","t":"42","fc":"rgb(0, 0, 0)","w":5},{"c":"rgb(0, 0, 255)","p":"nw","fc":"rgb(0, 0, 0)"}],"x":149.06285284387724,"y":5.308329729351229},{"id":"5467332","id":"8f0f5c30-d3d9-11e4-b3ef-53b449010d08","d":{"t":"c","active":true,"r":47},"type":"n","t":"asd","u":"p.png","g":[{"c":"#ccff99","p":"ne","t":"","fc":"rgb(0, 0, 0)","w":false},{"p":"nw","fc":"rgb(0, 0, 0)"}],"x":-164.24347467678655,"y":-32.64876353378594}],"combos":{"iop":[],"dfg":[]},"jk":{"width":966,"height":890,"zoom":5,"offsetX":905,"offsetY":744}}
What is typeof output? For parse() to work, it must be string but the dump in your question looks like it would return object. object means that the JSON has already been parsed and it's a JavaScript object.
So this would work:
var output = '{"type":"a","items":[{...}]}';
output = JSON.parse(output);
while this won't:
var output = {
"type":"a",
"items":[{...}]
};
output = JSON.parse(output);

How to select object in muti level array

I am attempting to get just the smiling array under tags then attributes. I have tried both to search and simply select. Every attempt results in an undefined variable. If you could explain how to select the smiling array that would be excellent!
{
"status": "success",
"photos": [{
"url": "http://tinyurl.com/673cksr",
"pid": "F#019cbdb135cff0880096136c4a0b9bad_3547b9aba738e",
"width": 375,
"height": 406,
"tags": [{
"uids": [],
"label": null,
"confirmed": false,
"manual": false,
"width": 30.67,
"height": 28.33,
"yaw": -16,
"roll": -1,
"pitch": 0,
"attributes": {
"face": {
"value": "true",
"confidence": 84
},
"smiling": {
"value": "false",
"confidence": 46
}
},
"points": null,
"similarities": null,
"tid": "TEMP_F#019cbdb135cff0880096136c00d500a7_3547b9aba738e_56.80_41.13_0_1",
"recognizable": true,
"center": {
"x": 56.8,
"y": 41.13
},
"eye_left": {
"x": 66.67,
"y": 35.71,
"confidence": 51,
"id": 449
},
"eye_right": {
"x": 50.67,
"y": 35.47,
"confidence": 57,
"id": 450
},
"mouth_center": {
"x": 60.8,
"y": 51.23,
"confidence": 53,
"id": 615
},
"nose": {
"x": 62.4,
"y": 42.61,
"confidence": 54,
"id": 403
}
}]
}],
"usage": {
"used": 21,
"remaining": 79,
"limit": 100,
"reset_time": 1390111833,
"reset_time_text": "Sun, 19 January 2014 06:10:33 +0000"
},
"operation_id": "edc2f994cd8c4f45b3bc5632fdb27824"
}
This particular code, will aggregate all the smiling attribute from the given object and return that as an Array.
map function will get smiling attribute from each and every tag
concat function will flatten all the attributes and returns a single array per photo.
reduce function will gather all the attributes all the photos and accumulate the result in result and that will be returned at the end.
var result = data.photos.reduce(function(result, currentPhoto) {
return result.concat(currentPhoto.tags.map(function(currentTag) {
return currentTag.attributes.smiling;
}));
}, []);
console.log(result);
Output
[ { value: 'false', confidence: 46 } ]
JSON.parse(json).photos[0].tags[0].attributes.smiling
obj.photos[0].tags[0].attributes.smiling
The best way would be to loop through the tags, instead of hardcoding 0 in there
obj.photos.forEach(function(photo){
photo.tags.forEach(function(tag){
tag.attributes.smiling; // here it is
});
});
It's a bit tricky since your JSON object is a mixture of objects and arrays, but here's how you would get to the "smiling" object (it's an object since there's no associative arrays in JavaScript):
var smiling_object = obj["photos"][0]["tags"][0]["attributes"]["smiling"];
Then you if you want to do something with it:
var some_var = smiling_object["value"];
var some_other_var = smiling_object["confidence"];
alert("The combined string is " + some_var + " and " + some_other_var);

json twitter query, parse to html feed

i am trying to build a hastag feed for twitter,
i already have read how to create the search query, and i have this json structure...
{
"completed_in": 0.026,
"max_id": 201961894368653313,
"max_id_str": "201961894368653313",
"next_page": "?page=2&max_id=201961894368653313&q=wearetwo&lang=en&rpp=100&include_entities=1",
"page": 1,
"query": "wearetwo",
"refresh_url": "?since_id=201961894368653313&q=wearetwo&lang=en&include_entities=1",
"results": [
{
{
"created_at": "Sat, 12 May 2012 01:06:19 +0000",
"entities": {
"hashtags": [
{
"text": "wearetwo",
"indices": [
12,
21
]
}
],
"urls": [
],
"user_mentions": [
{
"screen_name": "crifor",
"name": "Cristina Forlani",
"id": 110646291,
"id_str": "110646291",
"indices": [
3,
10
]
}
],
"media": [
{
"id": 201101250740240387,
"id_str": "201101250740240387",
"indices": [
34,
54
],
"media_url": "http:\/\/p.twimg.com\/Asp0haZCQAMC-Sq.jpg",
"media_url_https": "https:\/\/p.twimg.com\/Asp0haZCQAMC-Sq.jpg",
"url": "http:\/\/t.co\/1EXkTMYq",
"display_url": "pic.twitter.com\/1EXkTMYq",
"expanded_url": "http:\/\/twitter.com\/crifor\/status\/201101250740240384\/photo\/1",
"type": "photo",
"sizes": {
"small": {
"w": 340,
"h": 455,
"resize": "fit"
},
"large": {
"w": 765,
"h": 1024,
"resize": "fit"
},
"thumb": {
"w": 150,
"h": 150,
"resize": "crop"
},
"orig": {
"w": 765,
"h": 1024,
"resize": "fit"
},
"medium": {
"w": 600,
"h": 803,
"resize": "fit"
}
}
}
]
},
"from_user": "stevoltan",
"from_user_id": 165713968,
"from_user_id_str": "165713968",
"from_user_name": "Stefano Voltan",
"geo": null,
"id": 201116057396719616,
"id_str": "201116057396719616",
"iso_language_code": "en",
"metadata": {
"result_type": "recent"
},
"profile_image_url": "http:\/\/a0.twimg.com\/profile_images\/2163464409\/crepes_normal.jpg",
"profile_image_url_https": "https:\/\/si0.twimg.com\/profile_images\/2163464409\/crepes_normal.jpg",
"source": "<a href="http:\/\/twitter.com\/#!\/download\/iphone" rel="nofollow">Twitter for iPhone<\/a>",
"text": "RT #crifor: #wearetwo belle facce http:\/\/t.co\/1EXkTMYq",
"to_user": null,
"to_user_id": 0,
"to_user_id_str": "0",
"to_user_name": null
},
I need to extract the media url and text... can someone please help me.. i'm really new to this... i'd appreciate if you could show me a working example of this..at least the function...
This documentation will show you how to get the data into a format you can work with using jQuery:
http://api.jquery.com/jQuery.getJSON/
Something like:
$.getJSON('http://search.twitter.com/search.json?q=wearetwo&lang=en&result_type=recent&rpp=100&include_entities=true', function(data) {
var media_url = data.results.media.media_url;
var text = data.text;
});

Categories