Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a UL populated with the keys and values of a JSON with jQuery

What I have is this.

The HTML

<div id="catcher"></div>

The jQuery

jQuery.ajax({
  url:'./ajax.html', 
  async: true, 
  success: function(response){
    for (var key in response){
      jQuery('#catcher')
        .append("<ul>"+ key +"<li>" + response[key].toString() + "</li></ul>");
    }
  }
})

The JSON looks like

{
    "Item":"Item Name",
    "Item 1":"Item Name",
    "Item 2":"Item Name",
    "Item 3":"Item Name",
    "Item 4":"Item Name"
}

I would like to make a UL like this

  1. Item
    • Item Name
  2. Item 1
    • Item Name

And so on. What I am getting now is each individual letter of the value of the object and a numbers for the key. Instead I want them both to be equal to the strings.

like image 855
maxsands1503 Avatar asked Mar 10 '23 20:03

maxsands1503


2 Answers

You should try to add console.log(response) to your success callback. It will probably show that response is a string and not an object.

In this case you can add dataType:'json' to the jQuery.ajax(...) call, as explained here : how to parse json data with jquery / javascript?

like image 100
gregfqt Avatar answered Apr 09 '23 15:04

gregfqt


You're missing an outer ordered-list. If you append that first and change your looped append to have a nested <ul> you should get the structure you're looking for:

var data = {
  "Item": "Item Name",
  "Item 1": "Item Name",
  "Item 2": "Item Name",
  "Item 3": "Item Name",
  "Item 4": "Item Name"
}

$('#catcher').append('<ol></ol>');

for (var key in data) {
  $('#catcher ol').append('<li>' + key + '<ul><li>' + data[key] + '</li></ul></li>');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="catcher"></div>
like image 42
worc Avatar answered Apr 09 '23 13:04

worc