Decoding JSON on 9gag

I am trying to select a random image from the following URL:

In order to display it correctly, I need to determine the size of the image.

I am utilizing YQL to store the JSON result in a variable (referred to as source).

After replacing 'https' with 'http' and removing all backslashes, this is how I proceed:

var it = $.parseJSON(source);
var total = it.count-1;
var random = Math.floor((Math.random()*total)+0);     
var gagurl = it.items[random];
var gagurldecode = gagurl.replace('\\','');
gagurldecode = gagurldecode.replace('https','http'); //this is the image's URL 

Unfortunately, I am unable to retrieve the dimensions of this image.

   var img = new Image();
   img.src = gagurldecode;

The line alert(img.height); does not return anything.

If I change

img.src = gagurldecode;

to

img.src = 'http://d24w6bsrhbeh9d.cloudfront.net/photo/1777377_460s.jpg';

it works fine.

What am I doing incorrectly? PS: Apologies for any mistakes in my English!

Answer №1

This paragraph explains how the JSON data is interpreted and why certain lines of code may be unnecessary due to escaping slashes:

var gagurldecode = gagurl.replace('\\','');

The issue addressed here is that the height and width properties of an image are not immediately available until the image has been fully downloaded and examined. This process can occur asynchronously or synchronously depending on the browser's caching mechanism, as demonstrated in the following example:

img.onload = function() {
    alert(img.height);
}

The conclusion states that this approach will reliably yield the desired results.

Answer №2

What is the purpose of using replace calls in this scenario? It appears unnecessary since the slashes will automatically be unescaped when the string is parsed into JSON. Additionally, your replace calls are not utilizing replaceAll.

You may want to consider trying the following approach:

// Assume str contains the JSON received from the URL
var str = '{"items":["http:\/\/d24w6bsrhbeh9d.cloudfront.net\/photo\/5373376_460s.jpg","http:\/\/d24w6bsrhbeh9d.cloudfront.net\/photo\/2899638_460s_v1.jpg","http:\/\/d24w6bsrhbeh9d.cloudfront.net\/photo\/3196367_460s.jpg","http:\/\/d24w6bsrhbeh9d.cloudfront.net\/photo\/1777377_460s.jpg","http:\/\/d24w6bsrhbeh9d.cloudfront.net\/photo\/3233576_460s.jpg","http:\/\/d24w6bsrhbeh9d.cloudfront.net\/photo\/3101249_460s.jpg","http:\/\/d24w6bsrhbeh9d.cloudfront.net\/photo\/3279498_460s.jpg","http:\/\/d24w6bsrhbeh9d.cloudfront.net\/photo\/2487961_460s.jpg","http:\/\/d24w6bsrhbeh9d.cloudfront.net\/photo\/2693569_460s.jpg"],"layout":"list","count":9}'
var obj = JSON.parse(str);
var src = obj.items[~~(Math.random() * (obj.items.length - 1))];
img.src = src;

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Encountering excessive re-renders while using MUI and styled components

Hey there! I recently worked on a project where I used MUI (Material-UI) and styled-components to render a webpage. To ensure responsiveness, I made use of the useTheme and useMediaQuery hooks in my web application. My goal was to adjust the font size for ...

Initial position of jQuery slider

A while back, I came across some slider code on a website and copied it. Unfortunately, I can't seem to locate the source now. Here is the code snippet: slides.min.jquery.js $(function(){ $('#slides').slides({ preload: true, ...

Seeking out a particular key within a JSON object and then finding a match based on the id within that key's array - how can it be

Recently, I've been exploring JavaScript and encountering challenges when trying to apply array methods on objects. For instance, I received a fetch response and my goal is to extract the 'entries' key and then utilize the native Array.find( ...

Discover data using JavaScript recursively through paths

Here is the data structure I am working with: [ { name: 'root', children: [ { name: 'page', children: [ // and so on ] } ] } ] I am in need of a function that can retrieve ...

When clicking on an item in the wishlist, only the text for that specific item should change,

Hi all, I'm in need of some assistance. I have successfully created a wishlist toggle where clicking on the heart icon changes it from an outline to solid. However, my issue lies in changing the tooltip text from "add to wish list" to "added to wish l ...

Error caused by jQuery AJAX call: Receiving a 304 response code causes a problem

I am facing an issue with a script on my localhost that sends a GET request to the same domain. The response I am getting is a 304, which seems to be causing JQuery to treat it as an error. $(document).ready(function(){ $.ajax({ type: 'GE ...

What is the best way to hide or eliminate spinners/arrows in react-select?

I am currently utilizing react-select for my project, but I'm encountering an issue with removing the spinners/arrows from the dropdown menu. So far, I have successfully removed the default separator "|" and Dropdown Indicator using the following cod ...

Is it necessary for Webpack to package all dependent node modules with the final bundle in production mode?

It's common knowledge that when we run npm run build, React scripts utilize Webpack to create a bundle by examining the entire dependency graph (following imports) and generating a bundle.js which is then stored in the dist/build folder for production ...

Quiz results are incorrect

I've been working on creating a quiz application using JavaScript only, but I'm encountering an issue with the scoring. Initially, I set the correct variable to 0 and intended to increment it by 1 each time a correct answer is selected. However, ...

Assistance with designing in JavaScript and Python

Currently, I have a setup where my external website is extracting data from an iframe within our internal company intranet using Javascript. The extraction process is successful, but now I am faced with the challenge of accessing this harvested data in ord ...

Animation that increments to a predetermined value

I'm trying to create a counter animation that dynamically animates a value calculated by the checkboxes selected. The calculation is working fine, but the animation is not happening. http://jsfiddle.net/dbtj93kL/ $('input[type="checkbox"]&apo ...

An onClick event is triggered only after being clicked twice

It seems that the onClick event is not firing on the first click, but only works when clicked twice. The action this.props.PostLike(id) gets triggered with a delay of one click. How can I ensure it works correctly with just one click? The heart state togg ...

Filtering data from an Ajax request in Angular using a filter function with JSON

Hi everyone, I recently started learning AngularJS and created a basic item list with search functionality and pagination. Everything was working smoothly, so I decided to move my list outside the controller and store it as a JSON file. Here's what ...

A guide on utilizing the JsonProperty for accessing nested properties in JSON data

In attempting to deserialize a JSON code using Json.net, I encountered an issue with the cast property being nested within the credits property. To address this, I created a class named Actor to represent the cast members and included a list of this actor ...

How can I test for equality with an array item using v-if in Vue.js?

Currently, I am facing a challenge in my Vue.js project where I need to determine if a number is equal to an element within an array. Here is the code snippet that I am working with: <div v-if="someValue != arrayElement"> // </div> I am st ...

Can one manipulate the simulation to make isTrusted=true a reality?

Is there a way to simulate an isTrusted=true in touchStart event triggering? Are there any libraries or workarounds that can make this achievable? When I run the touchStart event programmatically versus physically triggering it, the output differs. Below ...

Utilizing jQuery for asynchronous image uploading

Just started learning jQuery and I'm having trouble uploading a jpg image file using the ajax method. It seems like it's not working properly. Can anyone guide me through this process? HTML <form action="" method="POST" enctype="multipart/fo ...

A guide to using jqGrid: Retrieve the value of a particular cell by double clicking on a row

Is there a way to implement a feature where users can double click on any part of a row and have it open a new HTML page based on the specific content in a cell? For example, I have a table with different counties in New York listed in separate rows: Coun ...

Is there a way to retrieve the previous value in an input field's onChange event?

I am working with inputs in a React project and have assigned a function to their onChange event. While I have been able to access the current value, I am now looking for a way to retrieve the previous value as well. The reason I need the old value is bec ...

Creating a new object through manipulation of existing objects

In my attempt to transform an existing object into a new object structure, I am facing some challenges. Here is the current data set: const jsonStructure = { "a11/a22/animations": "snimations", "a11/a22/colours": "sl/colours", "a11/a22/fonts" ...