0

Sorry, this might seem like a simple question but I am trying to put a javascript variable into a line of code from a JSON request.

Variable var name = "BTC"; Although I am hoping to change this value from BTC to another variable that can be changed if I can get this to work.

document.getElementById("img").src = 'https://www.cryptocompare.com'+img2.Data.[HERE].ImageUrl;

I have tried:

document.getElementById("img").src = 'https://www.cryptocompare.com'+img2.Data.+name+.ImageUrl;

document.getElementById("img").src = 'https://www.cryptocompare.com'+img2.Data.name.ImageUrl;

document.getElementById("img").src = 'https://www.cryptocompare.com'+img2.Data.[name].ImageUrl;

document.getElementById("img").src = 'https://www.cryptocompare.com'+img2.Data+name+ImageUrl;

and many more, although i can't get any of them to work. But when i put:

document.getElementById("img").src = 'https://www.cryptocompare.com'+img2.Data.BTC.ImageUrl;

it works. I have tried looking for hours on the internet unable to find the answer.

If it is any help the JSON file I am trying to access is: https://www.cryptocompare.com/api/data/coinlist/

(you may want to use a JSON parsing extension as it is hard to read)

Also my current code:

<script>

  var oReq = new XMLHttpRequest();
   oReq.open("GET", "https://www.cryptocompare.com/api/data/coinlist/");
   oReq.onload = function(){
      var img2 = JSON.parse(oReq.responseText);
      renderHTML(img2);
      }
        oReq.send();

        function renderHTML(img2){
        var htmlString = "";
        var name = "BTC";
        document.getElementById("img").src = 'https://www.cryptocompare.com'+img2.Data.BTC.ImageUrl;

        }
 </script>

<img src="" id="img"></img>

Thanks, I would appreciate any answers

Kaeder
  • 5
  • 2

1 Answers1

3

You were very close to solution, You are not using Bracket Notation correctly

img2.Data[name].ImageUrl

instead of

img2.Data.[name].ImageUrl
Satpal
  • 132,252
  • 13
  • 159
  • 168