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

Time:12-16

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" >
    <ul>
</div>
<div id="2" >
    <ul>
</div>

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

CodePudding user response:

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.

CodePudding user response:

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);
  }
});
  • Related