How can I traverse a json array and get its values to show them in the view?

15

My method for accessing a json url is as follows and it works, but now I want to run the json with a for and its'.lenght' but I could not.

The json I want to get the urls from is the following

link

<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js</scr>
<div id="success">
<div id="artisturl"></div>
</div>

$.ajax({
   type : 'GET',
   url : 'https://api.spotify.com/v1/search',
   data : {'q':'coldplay',
   'type':'artist'
   },
   dataType : 'json',
   success : function(data) {
      $('#success #artisturl').html(data.artists.items[0].uri) ;
   },
}) ;
    
asked by Diego 24.04.2016 в 06:20
source

2 answers

13

And why use jQuery when you can use native JavaScript?
Here is a solution that does not require external libraries:

for(const i = 0; i < data.artists.items.length; i++) {
    console.log(data.artists.items[i].href);  // (o el campo que necesites)
}

I know that you are already using jQuery, but I am in favor of using native tools whenever I can (although I understand that it is in terms of tastes). Personally, it does not seem more complex than the solution with jQuery, and so you are more aware of your code.

By the way, you do not have to parse the JSON, since what data is already an object.

    
answered by 25.04.2016 / 20:17
source
6

You can do with each one of jquery:

$.each(data, function(i, item) {
    console.log(item);
});

For example from this link: link

    
answered by 24.04.2016 в 08:06