Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
255 views
in Technique[技术] by (71.8m points)

arrays - How to parse JSON from API

Well, I have created an API and the output from http://localhost/lsapp4/public/api/articles in Postman is as follows:

{
"data": [
    {
        "id": 1,
        "title": "Demo Article-1",
        "body": "Happy Holidays1"
    },
    {
        "id": 2,
        "title": "Demo Article-2",
        "body": "Happy Holidays2"
    },
    {
        "id": 3,
        "title": "Demo Article-3",
        "body": "Happy Holidays3"
    }
],
"links": {
    "first": "http://lsapp4.test/api/articles?page=1",
    "last": "http://lsapp4.test/api/articles?page=2",
    "prev": null,
    "next": "http://lsapp4.test/api/articles?page=2"
},
"meta": {
    "current_page": 1,
    "from": 1,
    "last_page": 2,
    "path": "http://lsapp4.test/api/articles",
    "per_page": 3,
    "to": 3,
    "total": 4
}

}

How can I parse the title and body iteratively? I tried to do it like:

$.getJSON("http://localhost/lsapp4/public/api/articles",function(regen){
    var i=0;
    $.each(regen,function(index,item)
    {
        alert(item[i].title);
        i=i+1;
    });
});

But it did not work.

question from:https://stackoverflow.com/questions/65545486/how-to-parse-json-from-api

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your API is returning an object that contains an array in a field called data. You need to perform the $.each on this data field. You also do not need to reference i in the call to item.title. See sample code below:

var regen = {
  "data": [{
      "id": 1,
      "title": "Demo Article-1",
      "body": "Happy Holidays1"
    },
    {
      "id": 2,
      "title": "Demo Article-2",
      "body": "Happy Holidays2"
    },
    {
      "id": 3,
      "title": "Demo Article-3",
      "body": "Happy Holidays3"
    }
  ],
  "links": {
    "first": "http://lsapp4.test/api/articles?page=1",
    "last": "http://lsapp4.test/api/articles?page=2",
    "prev": null,
    "next": "http://lsapp4.test/api/articles?page=2"
  },
  "meta": {
    "current_page": 1,
    "from": 1,
    "last_page": 2,
    "path": "http://lsapp4.test/api/articles",
    "per_page": 3,
    "to": 3,
    "total": 4
  }
}

// Omitted $.getJSON for testing and demo purposes.
// Corrected code is also below. 
$.each(regen.data, function(index, item) {
  alert(item.title);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...