最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Parse JSON foreach with JS, shows HTML list - Stack Overflow

programmeradmin3浏览0评论

I am currently trying to parse a JSON with JavaScript. My issue is that I'd like the output to look like this:

<li>AppName1</li>
<li>AppName2</li>
<!-- and so on... -->

However it just does not work and I don't know how to achieve that. This is the object deserialized from the JSON response:

{
  "data": [{
    "AppId": 1,
    "AppName": "AppName1",
    "AppSize": "2.1"
  }, {
    "AppId": 2,
    "AppName": "AppName2",
    "AppSize": ""
  }]
}

This is my .js file:

var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
  if (this.readyState == 4 && this.status == 200) {
    var myObj = JSON.parse(this.responseText);
    document.getElementById("test").innerHTML = myObj.AppName;
  }
};
xmlhttp.open("GET", "json.json", true);
xmlhttp.send();

This is in my HTML file

<p id="test"></p>

Any help would be appreciated as I really cannot seem to understand this a single bit. Thank you so much!

I am currently trying to parse a JSON with JavaScript. My issue is that I'd like the output to look like this:

<li>AppName1</li>
<li>AppName2</li>
<!-- and so on... -->

However it just does not work and I don't know how to achieve that. This is the object deserialized from the JSON response:

{
  "data": [{
    "AppId": 1,
    "AppName": "AppName1",
    "AppSize": "2.1"
  }, {
    "AppId": 2,
    "AppName": "AppName2",
    "AppSize": ""
  }]
}

This is my .js file:

var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
  if (this.readyState == 4 && this.status == 200) {
    var myObj = JSON.parse(this.responseText);
    document.getElementById("test").innerHTML = myObj.AppName;
  }
};
xmlhttp.open("GET", "json.json", true);
xmlhttp.send();

This is in my HTML file

<p id="test"></p>

Any help would be appreciated as I really cannot seem to understand this a single bit. Thank you so much!

Share Improve this question edited Feb 15, 2019 at 12:40 Leon Mlaiel asked Feb 15, 2019 at 12:29 Leon MlaielLeon Mlaiel 631 silver badge6 bronze badges 2
  • 1 Please put a copy of the JSON in your question rather than a link that may not exist later. Do you want both a pure JavaScript answer and a jQuery one? – Mark Schultheiss Commented Feb 15, 2019 at 12:34
  • @MarkSchultheiss Did so! JavaScript is preferred but a jQuery answer could be both helpful and interesting – Leon Mlaiel Commented Feb 15, 2019 at 12:43
Add a ment  | 

5 Answers 5

Reset to default 2

Firstly note that you can only have li elements as children of <ul> or <ol>, so the p element needs to be changed.

The AppName property is part of the objects within data, so you will need to either loop through them:

myObj.data.forEach(function(o) {
   document.getElementById("test").innerHTML += '<li>' + o.AppName + '</li>';
}

Or access them, individually by index:

document.getElementById("test").innerHTML = '<li>' + myObj.data[0].AppName + '</li>'; // first item only

var myObj = {
  "data": [{
    "AppId": 3,
    "AppName": "AnimojiStudio",
    "AppSlug": "animojistudio",
    "AppIcon": "https:\/\/img.lmdinteractive.pro\/icons\/animojistudio.png",
    "AppUrl": "https:\/\/ipa.lmdinteractive.pro\/ipa\/appstore\/animojistudio.ipa",
    "AppVersion": "1.2.2",
    "AppSize": "2.1"
  }, {
    "AppId": 2,
    "AppName": "Cute Cut Pro",
    "AppSlug": "cute-cut-pro",
    "AppIcon": "http:\/\/is2.mzstatic.\/image\/thumb\/Purple118\/v4\/03\/70\/69\/03706968-2399-a1d8-e7c4-12897394ead9\/source\/512x512bb.jpg",
    "AppUrl": "https:\/\/ipa.lmdinteractive.pro\/ipa\/appstore\/cutecutpro.ipa",
    "AppVersion": "",
    "AppSize": ""
  }]
}

document.getElementById("test").innerHTML = '<li>' + myObj.data[0].AppName + '</li>';
<ul id="test"><li>

If you just want a list of the AppName properties, you could do something like the below with jQuery. See the ments in the code for details:

// Below is the JSON string from the OP's link
let json = '{"data":[{"AppId":3,"AppName":"AnimojiStudio","AppSlug":"animojistudio","AppIcon":"https:\/\/img.lmdinteractive.pro\/icons\/animojistudio.png","AppUrl":"https:\/\/ipa.lmdinteractive.pro\/ipa\/appstore\/animojistudio.ipa","AppVersion":"1.2.2","AppSize":"2.1"},{"AppId":2,"AppName":"Cute Cut Pro","AppSlug":"cute-cut-pro","AppIcon":"http:\/\/is2.mzstatic.\/image\/thumb\/Purple118\/v4\/03\/70\/69\/03706968-2399-a1d8-e7c4-12897394ead9\/source\/512x512bb.jpg","AppUrl":"https:\/\/ipa.lmdinteractive.pro\/ipa\/appstore\/cutecutpro.ipa","AppVersion":"","AppSize":""}]}';

// Parse the JSON string into a JS object
json = JSON.parse(json);
let html = "";

// Loop over the object and append a list item for each AppName property.
$.each(json.data, function (index, item) {
    html += "<li>" + item.AppName + "</li>";
});

// Append the list to the div.
$("#container").append(html);
<script src="https://cdnjs.cloudflare./ajax/libs/jquery/1.12.3/jquery.min.js"></script>
<div id="container"></div>

Using forEach loop and append. Inserting li inside a p tag is not a good idea even though it works. Convert the p into a ul/ol

var data = {
  "data": [{
    "AppId": 3,
    "AppName": "AnimojiStudio",
    "AppSlug": "animojistudio",
    "AppIcon": "https:\/\/img.lmdinteractive.pro\/icons\/animojistudio.png",
    "AppUrl": "https:\/\/ipa.lmdinteractive.pro\/ipa\/appstore\/animojistudio.ipa",
    "AppVersion": "1.2.2",
    "AppSize": "2.1"
  }, {
    "AppId": 2,
    "AppName": "Cute Cut Pro",
    "AppSlug": "cute-cut-pro",
    "AppIcon": "http:\/\/is2.mzstatic.\/image\/thumb\/Purple118\/v4\/03\/70\/69\/03706968-2399-a1d8-e7c4-12897394ead9\/source\/512x512bb.jpg",
    "AppUrl": "https:\/\/ipa.lmdinteractive.pro\/ipa\/appstore\/cutecutpro.ipa",
    "AppVersion": "",
    "AppSize": ""
  }]
}
data.data.forEach(e =>$('#test').append('<li>' + e.AppName + '</li>' + "<br>"))
<script src="https://cdnjs.cloudflare./ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul id="test"></ul>

You can use map() since you have an array inside myObj. What you want to do is returning a li with AppName value

var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
  if (this.readyState == 4 && this.status == 200) {
    var myObj = JSON.parse(this.responseText);
    var ul = document.getElementById("myUl");
    var li = document.createElement('li');
    var data = myObj.data;
    data.map(app => {
        li.textContent = app.AppName;
        ul.appendChild(li);
    })
  }
};
xmlhttp.open("GET", "json.json", true);
xmlhttp.send();

You have your object, and it is parsed so let's concentrate on doing something with that object:

var myObj = {
  "data": [{
    "AppId": 1,
    "AppName": "AppName1",
    "AppSize": "2.1"
  }, {
    "AppId": 2,
    "AppName": "AppName2",
    "AppSize": ""
  }]
};

Now we have that, let's use it in different ways. myObj contains an array called data here. That array is an array of JavaScript objects, each with properties like "AppId", "AppName" etc. which we can access either directly or through an index. So, let's put up some examples of how to do that. Comments in the code

var myObj = {
  "data": [{
    "AppId": 1,
    "AppName": "AppName1",
    "AppSize": "2.1"
  }, {
    "AppId": 2,
    "AppName": "AppName2",
    "AppSize": ""
  }]
};
// Here I create a Bootstrap tab and contents
// call to create a new element on the DOM
function additem(item) {
  let lt = $('#list-tab');
  let ltc = $('#debug-tabContent');
  let thing = item.name;
  let thingId = "list-" + thing;
  let thingTabId = thingId + "-list";
  let ttab = $('<a />')
    .addClass('list-group-item list-group-item-action')
    .data('toggle', "list")
    .prop("id", thingTabId)
    .attr('role', 'tab')
    .prop('href', '#' + thingId)
    .html(item.name);
  ttab.appendTo(lt);
  let lc = $('<div />')
    .addClass('tab-pane fade')
    .prop("id", thingId)
    .attr('role', 'tabpanel')
    .text(JSON.stringify(item.obj));
  // .text("test");
  lc.appendTo(ltc);
}
// * cheat, put the objects in a bootstrap tab content list
additem({
  name: "myObj",
  obj: myObj
});
additem({
  name: "myObjW",
  obj: window["myObj"]
});
additem({
  name: "data",
  obj: myObj.data
});
additem({
  name: "data0",
  obj: myObj.data[0]
});
additem({
  name: "AppName",
  obj: myObj.data[0].AppName
});

// pure JS walk
// Here I create a LI list as a Bootstrap list group
let len = myObj.data.length;
let myP = document.getElementById("test");
let myReg = document.getElementById("mylist-reg");
let newUl = document.createElement("ul");
newUl.classList.add('list-group');
newUl.classList.add('list-group-primary');
for (var i = 0; i < len; i++) {
  let newLi = document.createElement("li");
  let newContent = document.createTextNode(myObj.data[i].AppName);
  newLi.appendChild(newContent);
  newLi.setAttribute("id", "app-" + myObj.data[i].AppId); //has to be unique
  newLi.setAttribute("class", "list-group-item");
  newUl.appendChild(newLi);
}
// put the list after the paragraph
document.body.insertBefore(newUl, myP);

let myLast = document.getElementById("app-2");
myLast.classList.add("active");
//activate the bootstrap tab clicks
$('#list-tab').on('click', 'a', function(e) {
  e.preventDefault();
  $(this).tab('show');
});

// just do it as strings
let html = "";
for (var i = 0; i < len; i++) {
  let textel = "<li id='app-js-" + myObj.data[i].AppId + "'>" + myObj.data[i].AppName + "</li>";
  html = html + textel;
}
myReg.innerHTML = html;

// jQuery, similar to prior
$.each(myObj.data, function(index, el) {
  let textel = "<li id='app-jq-" + el.AppId + "'>" + index + ":" + el.AppName + "</li>";
  $('#mylist-jq').append(textel);
});

// jQuery, similar to prior
$.each(myObj.data, function(index, el) {
  let elid = 'app-jq2-' + el.AppId;
  $("<li />").prop("id", elid).text(el.AppName)
    .appendTo('#mylist-jq2');
});
.list-group-item {
  border: 1px lime solid
}

.list-item-last {
  color: red;
}
<script src="https://cdnjs.cloudflare./ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare./ajax/libs/twitter-bootstrap/4.2.1/css/bootstrap.min.css" />

<ul id="mylist-reg"></ul>
<ul id="mylist-jq"></ul>
<ul id="mylist-jq2"></ul>
<p id="test" class="row">put stuff after here</p>
<div class="row">
  <div class="col-4">
    <div class="list-group" id="list-tab" role="tablist">
    </div>
  </div>
  <div class="col-8">
    <div class="tab-content" id="debug-tabContent">
      <div class="tab-pane fade show active" id="list-home" role="tabpanel" aria-labelledby="list-home-list">Click a tab to see one.</div>

    </div>
  </div>
</div>

<script src="https://cdnjs.cloudflare./ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare./ajax/libs/twitter-bootstrap/4.2.1/js/bootstrap.bundle.min.js"></script>

发布评论

评论列表(0)

  1. 暂无评论