Warm tip: This article is reproduced from stackoverflow.com, please click
jquery json

Cannot convert json to html list using jquery

发布于 2020-03-27 10:25:08

I'd like to convert a search result received from server to unordered list:

function searchSuccess(json, textStatus, jqXHR) {
  console.log('json is:', json);
  var html= "<ul>";
  Object.keys(json).forEach(function(key, val) { 
    html += "<li><a href=\'" + val['slug'] + "\'>" + val['title'] +"</a></li>";    
  });
  html +="</ul>"
  $('#search-results').append(html);
}

The json, as I see in the console is like:

json is: [{"title":"Hello World","slug":"hello-world"},{"title":"I'm a title","slug":"I-am-title"}]

However, instead of the linked li , a list of undefined is rendered.

What is wrong here? How can I fix it?

Questioner
grhn
Viewed
86
Mark Baijens 2019-07-03 23:20

You had an array list with javascript object in your json. These codes works:

  • Little adjustment to your code:

var json = '[{"title":"Hello World","slug":"hello-world"},{"title":"I\'m a title","slug":"I-am-title"}]';

function searchSuccess(json) {
  console.log('json is:', json);
  var html= "<ul>";
  jsonObject = JSON.parse(json);
  
  jsonObject.forEach(function(searchresult) { 
    html += "<li><a href=\'" + searchresult.slug + "\'>" + searchresult.title +"</a></li>";    
  });
  html +="</ul>"
  $('#search-results').empty().append(html);
}

searchSuccess(json);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="search-results"></div>
  • Nicer jQuery way:

var json = '[{"title":"Hello World","slug":"hello-world"},{"title":"I\'m a title","slug":"I-am-title"}]';

function searchSuccess(json) {
  var $ul = $('<ul>');
  jsonObject = JSON.parse(json);
  
  jsonObject.forEach(function(searchresult) {
    var $li = $('<li>');
    var $a = $('<a>');
    $a.attr('href', searchresult.slug)
    $a.text(searchresult.title);
    $li.append($a);
    $ul.append($li);
  });
  $('#search-results').empty().append($ul);
}

searchSuccess(json);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="search-results"></div>