JSON parsing

Object.keys(val)

json data is as follows

[
{"id":0,"imageLink":"/images/funny-cat.jpg",
    "codeNames":["Juggernaut","Mrs. Wallace","Buttercup"]},
{"id":1,"imageLink":"/images/grumpy-cat.jpg",
    "codeNames":["Oscar","Scrooge","Tyrion"]},
{"id":2,"imageLink":"/images/mischievous-cat.jpg",
    "codeNames":["The Doctor","Loki","Joker"]}
]

.forEach()function to loop through the JSON data and write it to the htmll variable.  

<div class="container-fluid">
  <div class = "row text-center">
    <h2>Cat Photo Finder</h2>
  </div>
  <div class = "row text-center">
    <div class = "col-xs-12 well message">
      The message will go here
   </div>
  </div>
  <div class = "row text-center">
    <div class = "col-xs-12">
      <button id = "getMessage" class = "btn btn-primary">
        Get Message
      </button>
    </div>
  </div>
</div>

<script>
  $(document).ready(function() {
    $("#getMessage").on("click", function() {
      $.getJSON("/json/cats.json", function(json) {
      var html = "";
      json.forEach(function(val) {
        var keys = Object.keys(val);
        html += "<div class = 'cat'>";
        keys.forEach(function(key) {
          html += "<b>" + key + "</b>: " + val[key] + "<br>";
        });
        html += "</div><br>";
      });
        $(".message").html(html);

      });
    });
  });
</script>

We filter out images where the "id" key has a value of 1.

json = json.filter(function(val) {
  return (val.id !== 1);
});

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325137709&siteId=291194637