简体   繁体   中英

Basic JSON: How do I display the following JSON as a list of links?

I have the following JSON list of URLs:

{
"1": [
    {"name": "link 1",
        "url": "https://url-for-link-1.com"},
    {"name": "link 2",
        "url": "https://url-for-link-2.com"},
    {"name": "link 3",
        "url": "https://url-for-link-3.com"}
    ],
"2": [
    {"name": "link 4",
        "url": "https://url-for-link-4.com"},
    {"name": "link 5",
        "url": "https://url-for-link-5.com"},
    {"name": "link 6",
        "url": "https://url-for-link-6.com"}
    ]   
}

And I have the following javascript:

$.getJSON("/assets/json/resource-links.json", function(data) {
    var items = [];
    $.each(data, function(id, name, url) {
        items.push("<li>" + "< a href='" + url + "'>"
            name + "</a>" + "</li>");
    });
    $("<ul/>", {
        html: items.join("")
    }).appendTo("#" + id);
});

I have DIVs with ids like this:

<div id="1" class="links">
    <ul>
</div>
<div id="2" class="links">
    <ul>
</div>

How do I read my list of JSON and put them into the DIVs?

You can try this:

$.getJSON( "test.json", function( data ) {
    $.each( data, function( id, links) {
        $.each(links, function (i, elem){
            $(`#${id} ul`).append(`<li><a href="${elem.url}">${elem.name}</a></li>`)
        })
    });
});

Because you have nested objects you should have nested loops. When it's iterating your links you can easily append li to the specified ul which has a as a child in it.

You can simply use a basic function like this

$.getJSON('/assets/json/resource-links.json', function (data) {
  for (const key in data) {
    const links = data[key];
    const div = document.getElementById(key);
    const ul = document.createElement('ul');

    for (const link of links) {
      const li = document.createElement('li');
      const a = document.createElement('a');
      a.href = link.url;
      a.textContent = link.name;
      li.appendChild(a);
      ul.appendChild(li);
    }

    div.appendChild(ul);
  }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM