How to generate a li from this JSON [closed]

-4

I am making a request to get this JSON , and would like to know how to mount a li using this request

var url = "data.json";

        var httpRequest = new XMLHttpRequest();
        httpRequest.open("GET", url);
        httpRequest.responseType = "json";
        httpRequest.addEventListener("readystatechange", function () {
          if (httpRequest.readyState == 4){
            if (httpRequest.status == 200){
              console.log(httpRequest.response);
              console.log(httpRequest.response.headDocument);
              console.log(httpRequest.response.headDocument.authors);
              console.log(httpRequest.response.headDocument.content);
            } else {
                console.log("fiz algo errado xD")
            }
          }
        });

        httpRequest.send();
    
asked by anonymous 15.02.2016 / 17:04

1 answer

0

You can make a foreach to get the data:

//...
if (httpRequest.status == 200){
    httpRequest.response.headDocument.content.forEach(function(o){
        console.log("source: " + o.source);
        console.log("collectionId: " + o.collectionId);
        console.log("generator ID: " + o.content.generator.id);
        console.log("parent ID: " + o.content.parentId);
        //...
    });
}
//...

Your problem is understanding how to navigate within a json object. By understanding this, you will be able to build your list.

See the json that was used in the question, there is a collection of json objects within your json array httpRequest.response.headDocument.content .

JSON arrays are delimited by brackets [], with their elements separated by commas:

{
    headDocument: { //objecto json
        content: [ //array json com uma coleção de objectos json
            { source: 1,collectionId: "155985417", //... }, //objecto json
            { source: 2,collectionId: "556454847", //... }, //objecto json
            //...
        ]
    }
 }

So we use forEach to get access to all elements of the content array. Each element of this array is a json object that is passed as a parameter to the callback function:

httpRequest.response.headDocument.content.forEach(function(o){
    //O parâmetro "o" é um objecto json
}

As the "o" parameter is a json object, we can navigate its properties:

o.source //source é uma propriedade do objecto "o"
o.collectionId //collectionId é uma propriedade do objecto "o"
//...
    
15.02.2016 / 19:36